python
33 lines · 1 tab
Dr. Elena Vasquez
Apr 2026
1 tab
import torch
best_val_loss = float('inf')
for epoch in range(1, num_epochs + 1):
model.train()
train_loss = 0.0
for batch in train_loader:
inputs, targets = [item.to(device) for item in batch]
optimizer.zero_grad(set_to_none=True)
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
train_loss += loss.item() * inputs.size(0)
model.eval()
val_loss = 0.0
with torch.no_grad():
for batch in valid_loader:
inputs, targets = [item.to(device) for item in batch]
outputs = model(inputs)
loss = criterion(outputs, targets)
val_loss += loss.item() * inputs.size(0)
val_loss /= len(valid_loader.dataset)
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save({'model_state': model.state_dict()}, 'best_model.pt')
scheduler.step(val_loss)
print(f'epoch={epoch} val_loss={val_loss:.4f}')
1 file · python
Explain with highlit
The training loop is where research code either becomes maintainable or turns into a mess. I keep it explicit: train phase, validation phase, scheduler step, metric tracking, and checkpoint saving. That structure pays off immediately when experiments fail halfway through or need to be resumed on another machine.
Related snips
ruby
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
rails
activemodel
form-object
by codesnips
3 tabs
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation Example</title>
<style>
HTML forms with validation and accessibility
html
forms
validation
by Alex Chang
1 tab
typescript
import axios from 'axios';
export type NormalizedErrors = {
fields: Record<string, string>;
formLevel: string | null;
};
Frontend: normalize and display server validation errors
ux
typescript
react
by codesnips
3 tabs
php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
Laravel form requests for validation
laravel
validation
form-requests
by Carlos Mendez
2 tabs
python
import torch.nn as nn
class SmallCNN(nn.Module):
def __init__(self, num_classes: int) -> None:
super().__init__()
self.features = nn.Sequential(
Convolutional neural networks for image classification in PyTorch
pytorch
cnn
computer-vision
by Dr. Elena Vasquez
1 tab
ruby
class ReindexCheckpoint < ApplicationRecord
enum status: { idle: 0, running: 1, done: 2, failed: 3 }
validates :index_name, presence: true, uniqueness: true
def self.for(index_name)
Safer Background Reindex: slice batches + checkpoints
rails
reliability
elasticsearch
by codesnips
4 tabs
Share this code
Here's the card — post it anywhere.