Module contents
Lesson 30 of 33Core 115 min

Video and temporal modeling

Study optical flow, two-stream and spatiotemporal convolutions, video transformers, masked video pretraining and temporal sampling.

After this lesson you can

  • Derive optical flow from brightness constancy and implement pyramidal Lucas–Kanade.
  • Compare 3D, (2+1)D and two-stream networks by parameters, cost and inductive bias.
  • Implement divided space–time attention and tubelets and compare cost with joint attention.
  • Explain why video masking can use very high mask ratios.
  • Design and evaluate frame-sampling strategies for a task.

Before you start

One image does not reveal whether a hand opens or closes

Two videos can contain the same central frame of a hand and differ only in motion order. Appearance classification can succeed if background or object correlates with the label, but does not show the model uses the sequence. For a robot, when the object was released and what happened afterward matter: a static frame need not answer either question.

InteractiveA window over an edge
  • true velocity
  • estimate

The window is idealized: showing an endpoint assumes a second independent noiseless gradient. In real images the structure matrix must be checked.

30
0.8
-0.4
0.8
Normal component0.49
Independent gradients1
Estimate(0.43, 0.25)
Change velocity, orientation and radius. With only an edge the ideal model shows the minimum-norm solution; when an endpoint appears it assumes a second independent gradient. This is not a real-video measurement.

Motion and the aperture problem

Optical flow describes apparent pixel displacement between two instants, not necessarily an object’s 3D velocity. Under brightness constancy, for a visible point moving (u,v)(u,v) during Δt\Delta t,

I(x+uΔt,y+vΔt,t+Δt)=I(x,y,t).I(x+u\Delta t,y+v\Delta t,t+\Delta t)=I(x,y,t).

If II is differentiable and displacement small, first-order Taylor expansion and division by Δt\Delta t give Ixu+Iyv+It≃0I_xu+I_yv+I_t\simeq0. Lighting changes, occlusion, reflections, and large motion violate the assumptions. An isolated edge fixes only projection (u,v)⋅∇I(u,v)\cdot\nabla I: infinitely many tangential velocities produce the same equation. The figure shows the minimum-norm solution for one gradient, not certain motion reconstruction.

Lucas–Kanade assumes constant flow within a window. For pixels ii, stack Ai=(Ix,i,Iy,i)\mat{A}_i=(I_{x,i},I_{y,i}) and bi=−It,ib_i=-I_{t,i}; then minimize ∥Av−b∥2\norm{\mat{A}\vb{v}-\vb{b}}^2. If A\mat{A} has rank two, the solution is (A⊤A)−1A⊤b(\mat{A}\T\mat{A})\inv\mat{A}\T\vb{b}. On an edge rows are approximately parallel and the system is ill-conditioned; a corner provides gradients in two directions if contrast and texture suffice. A Gaussian pyramid reduces displacement at coarse levels and refines estimation through warping and new linearizations. It does not make occluded correspondences valid.

The matrix A⊤A\mat{A}\T\mat{A} summarizes window gradients. If one eigenvalue is near zero, one direction has very little information and noise can greatly change estimated velocity. A corner detector often requires both eigenvalues above a threshold; that threshold depends on scale, noise, and intensity. Increasing radius adds samples but may mix objects moving differently. The figure shows an ideal noiseless endpoint; confidence in a real scene requires inspecting the matrix, not just drawing an arrow.

In a pyramid, eight-pixel displacement at original resolution becomes about two pixels after two reductions by two. The coarse estimate is doubled when moving up each level and used to warp the second image before calculating correction. This still requires texture and a reasonable starting point. If a hand covers a block, pixels behind it are no longer observed: no valid correspondence can be recovered simply by averaging a larger window.

RAFT extracts features, builds correlations between pairs of positions, and iteratively updates flow with a recurrent unit. The paper reported EPE 2.855 pixels on Sintel final and F1-all error 5.10% on KITTI under its protocols; these published figures are not this lesson’s lab results. EPE is per-pixel Euclidean distance between estimated and reference flow; it does not itself measure robotic-policy success.

Flow scale must follow the image. If both dimensions are halved and a four-pixel displacement is calculated in the reduced image, that vector corresponds to eight original pixels. If width and height scale differently, scale each component by its own factor. A reference map can also contain invalid pixels due to occlusion or leaving the field of view; exclude or report them separately rather than silently assigning zero flow. Mean EPE can hide large errors concentrated on a small hand, so break it down by region and displacement magnitude.

A moving camera induces flow even when the world is static. Calibration and depth can help separate a component explained by camera motion, but neither global subtraction nor one planar transformation solves every scene with varying depth. Two pixels on the same object can move differently due to perspective or rotation, and a shadow can move without transporting matter. Flow is useful for tracking and temporal analysis; physical action needs additional geometry and contact information.

Two streams and convolutions with time

Two-stream networks separate an appearance branch from one receiving motion, such as optical flow. Simonyan and Zisserman studied this complementarity. Flow-estimator cost and error are also part of the system: a second branch does not obtain motion for free.

A spatiotemporal convolution with kernel kt×kh×kwk_t\times k_h\times k_w, CinC_{in} input channels and CoutC_{out} output channels has CinCoutktkhkwC_{in}C_{out}k_tk_hk_w weights, excluding biases. (2+1)D factorization first applies a spatial kernel with MM intermediate channels and then a temporal one: CinMkhkw+MCoutktC_{in}Mk_hk_w+MC_{out}k_t weights. A nonlinearity between steps means it is not simply one linear 3D convolution. Choose MM to compare similar budgets and count activations and operations, not just parameters. Tran and colleagues studied this factorization in residual networks.

Inflating a 2D layer repeats its kernel along ktk_t and divides each copy by ktk_t. For constant video without boundary effects, the temporal sum reproduces the original 2D response; without division the response is multiplied by ktk_t. I3D uses this idea to reuse image weights. SlowFast separates a slow temporal stream with greater spatial capacity from a fast lightweight stream: effectiveness depends on selected frequency, width, and fusion, not merely duplicating frames.

For scale, a convolution with Cin=64C_{in}=64, Cout=128C_{out}=128 and kernel 3×3×33\times3\times3 uses 221184 weights. With spatial and temporal steps of intermediate width M=128M=128, factorization uses 64⋅128⋅9+128⋅128⋅3=12288064\cdot128\cdot9+128\cdot128\cdot3=122880 weights. This example does not equalize budgets: it checks the formula. Adding normalization layers and nonlinearities changes capacity and memory. An experimental comparison should record intermediate size, activation count, and clip-reading and preparation cost.

The temporal branch of a two-stream network depends on how motion was computed and normalized. An estimator trained at another resolution, on synthetic images, or under different lighting can fail precisely on videos where the classifier needs help. Compare appearance alone, motion alone, and fusion on the same test set; also report flow-extraction time. If a branch wins only when reference uses future information unavailable online, its result does not describe the deployed system.

A three-step temporal convolution can see past, present, and future when centered at the current instant. For an immediate decision, that window introduces waiting or needs a causal version. Stacking layers increases effective temporal field, but contributing frame count also depends on stride, padding, and clip duration. Before comparing 3D and 2D networks, check covered interval and delay: improvement can come from seeing more future, not only a better representation.

Tokens and cost

A tubelet groups a block of τ\tau frames and a p×pp\times p spatial patch into a token. If dimensions divide evenly, T=T0/τT=T_0/\tau and N=(H/p)(W/p)N=(H/p)(W/p); there are TNTN tokens before special tokens. Padding and crops change that count. Divided space–time attention attends over time for each spatial position and then over space within each time. One pass lets information from another position and instant arrive in two hops, but is not generally equivalent to one joint attention matrix.

For one head, counting only query–key scores gives (TN)2(TN)^2 for joint attention and NT2+TN2NT^2+TN^2 for divided attention. This excludes projections, softmax, special-token attention, and value multiplications. With 16 frames of 224×224, two-frame tubelets and 16×16 patches, T=8T=8, N=196N=196 and there are 1568 tokens. Scores are 2458624 versus 319872, a ratio of about 7.686. TimeSformer studies divided attention; savings in that count do not guarantee equal accuracy or identical latency reduction on hardware.

InteractiveWhich patches can be consulted
  • selected
  • visible keys

The count sums query–key products for one head. It excludes projections and special tokens; divided attention includes both stages.

Pattern
Patch t/r/c2, 2, 2
Keys for this query64
Total scores4096
Select a point in the space–time grid. Compare joint attention, each divided stage, and a local neighborhood. Counts are exact for this four-time, 4×4-position cube without special tokens.

The masked video autoencoder reconstructs missing parts from visible tokens. VideoMAE studied tube masks and 90–95% mask ratios: temporal redundancy makes that regime possible in its experiments. Masking a spatial position at multiple instants prevents a nearly identical copy of the same patch in the next frame trivially revealing content. Latent-space prediction can choose another target representation, but depends on information retained in that space.

With a 90% mask, the encoder processes only the 10% visible patches in the configuration using that strategy; decoder and loss construction have their own costs. If a frame has 196 patches and there are eight temporal positions, there are 1568 positions; retaining about 157 does not mean perfectly reconstructing the remaining 1411. A fixed tube mask makes copying the same location from a nearby instant harder, but a static scene can have other redundant background clues. Changing the mask and measuring prediction on truly different sequences helps study the learned representation.

Reconstruction pretraining and supervised classification use different objectives. The first hides patches and learns to predict their content; the second replaces or tunes a head to distinguish labels. Low training reconstruction loss does not guarantee recognition of new actions or detection of when release occurred. To study transfer, compare pretrained weights with a reference initialization using the same split and budget, and keep pre-fine-tuning data separate.

Temporal sampling decides how many frames are observed and when. Sparse sampling covers more duration but can miss a brief event; dense sampling captures local motion but can omit context. Training and test should use declared frequency and duration distributions. To diagnose shortcuts, compare one image, reverse temporal order when the label permits, and evaluate background and object changes. A benchmark with correlated background can reward appearance without measuring motion understanding.

If eight images are taken four original intervals apart, first and last are separated by 28 intervals, not 32. At 30 frames per second that is about 0.93 s between endpoints. Changing spacing to eight covers about 1.87 s, but a very brief action between instants can be missed. Repeating an image to fill transformer input preserves shape but adds no motion evidence. When comparing four and eight images, state whether they cover the same duration or use the same spacing: these answer different questions.

Per-class accuracy helps distinguish these effects. An action characterized by object and background may be classified well from one frame; a pair like opening and closing may require temporal order, though an initial or final image can also reveal clues. Evaluate both directions with crossed positions, objects, and backgrounds. If a clip’s label is not reversible or reversal produces physically impossible motion, the result also measures that anomaly; do not automatically interpret it as order understanding.

InteractiveHow many frames to observe
t=1
t=2
t=3
t=4

Opening and closing share the same first frame within each pair. Past the end frame 16 repeats; displayed cost counts input values, not GPU time.

Task
Example
Frames
Spacing
Correct on test68 / 100
Features per clip3072
Paired synthetic opening/closing and color clips. A linear classifier was fitted on 140 clips and evaluated on 100 held out. Figures are from this example, not UCF101 or VideoMAE.

In this experiment each opening/closing pair shares its first frame and noise by construction. With one frame the classifier gets 50 of 100 correct; with eight consecutive frames it gets 97. The color task gets 100 with one frame in this artificial set. More samples increase input-value count, and two-step spacing covers more duration; beyond the clip’s end the last frame is repeated. Do not infer real-video accuracy or a universal frequency law from this example.

In the natural-video lab, all methods uniformly sample the interval between first and last available frame; with one sample the first is taken. This roughly equalizes temporal coverage of multi-sample clips, but not sample spacing or spatial resolution across architectures. Thirty validation clips suffice for a demonstration but are few for choosing among many decisions; a small improvement on 75 test clips may reflect sample variation. Report correct counts and denominator, and consider uncertainty intervals before generalizing.

Relationships between clips also matter. Two segments from one recording can share actor, camera, and setting; random splitting can inflate evaluation. Holding out groups per class reduces that leakage in this subset, though it does not guarantee actor or object independence across all classes. For robotics, add episodes from truly different cameras, objects, and locations and verify recording rights and provenance. Useful latency includes decoding and frame preparation as well as network forward pass.

Lab: registration and attention

The cell generates a textured image and shifts it five pixels right and three up. Each pyramid level estimates a global translation, so this checks the algorithm under constant motion, not dense flow or occlusions. Interpolation and boundaries introduce error. Endpoint error is compared with known translation.

[ ]Pyramidal Lucas-KanadeBrowser
import numpy as np
from scipy.ndimage import gaussian_filter, shift, map_coordinates
rng=np.random.default_rng(30)
first=gaussian_filter(rng.normal(size=(64,64)),1.0)
truth=np.array([5.,-3.]);second=shift(first,(truth[1],truth[0]),order=1,mode='nearest')
def lk_translation(first,second,levels=3,iterations=8):
    p1=[first];p2=[second]
    for _ in range(1,levels):
        p1.append(gaussian_filter(p1[-1],1)[::2,::2]);p2.append(gaussian_filter(p2[-1],1)[::2,::2])
    flow=np.zeros(2)
    for level in range(levels-1,-1,-1):
        if level<levels-1:flow*=2
        a=p1[level];b=p2[level];iy,ix=np.gradient(b);yy,xx=np.mgrid[:a.shape[0],:a.shape[1]]
        for _ in range(iterations):
            x=xx+flow[0];y=yy+flow[1];valid=(x>=1)&(x<a.shape[1]-2)&(y>=1)&(y<a.shape[0]-2)
            coords=[y[valid],x[valid]]
            bw=map_coordinates(b,coords,order=1);gx=map_coordinates(ix,coords,order=1);gy=map_coordinates(iy,coords,order=1)
            A=np.column_stack((gx,gy));delta,_,rank,_=np.linalg.lstsq(A,a[valid]-bw,rcond=None)
            if rank<2:raise ValueError('gradientes insuficientes')
            flow+=delta
    return flow
estimated=lk_translation(first,second)
print('verdadero:',truth,'estimado:',estimated.round(3),'EPE:',round(float(np.linalg.norm(estimated-truth)),4))

The following attention uses inputs as queries, keys, and values, without projections or additional heads. The second implementation uses masked matrices over the flattened sequence to verify that the divided operation performs the same transformation, not that it equals joint attention.

[ ]Joint and divided attentionBrowser
import numpy as np
def attention(x):
    scores=x@x.T/np.sqrt(x.shape[-1]);scores-=scores.max(axis=-1,keepdims=True)
    w=np.exp(scores);w/=w.sum(axis=-1,keepdims=True)
    return w@x
def divided_space_time_attention(x,T,N):
    x=np.asarray(x,dtype=float).reshape(T,N,-1)
    temporal=np.stack([attention(x[:,n,:]) for n in range(N)],axis=1)
    return np.stack([attention(temporal[t]) for t in range(T)],axis=0)
def masked_attention(x,mask):
    scores=x@x.T/np.sqrt(x.shape[-1]);scores=np.where(mask,scores,-np.inf)
    scores-=scores.max(axis=-1,keepdims=True);w=np.exp(scores);w/=w.sum(axis=-1,keepdims=True)
    return w@x
T,N,D=3,4,5;x=np.random.default_rng(30).normal(size=(T,N,D));flat=x.reshape(T*N,D)
times=np.repeat(np.arange(T),N);places=np.tile(np.arange(N),T)
ref=masked_attention(masked_attention(flat,places[:,None]==places[None,:]),times[:,None]==times[None,:]).reshape(T,N,D)
divided=divided_space_time_attention(x,T,N);joint=attention(flat).reshape(T,N,D)
print('máxima diferencia frente a máscaras:',np.max(np.abs(divided-ref)))
print('norma diferencia con conjunta:',round(float(np.linalg.norm(divided-joint)),6))
print('puntuaciones conjunta/dividida:',(T*N)**2,N*T*T+T*N*N)

The next cell reproduces the figure’s experiment. Each seed generates two clips with the same noise and, for motion, the same first frame. The linear classifier uses ridge regression on flattened pixels; its test seeds differ. The color task and geometric shapes are constructed to teach a distinction, so their accuracy does not estimate natural-video performance.

[ ]Synthetic sampling and classificationBrowser
import numpy as np
def make_pair(seed,task):
    rng=np.random.default_rng(seed);base=rng.uniform(.38,.62);amplitude=rng.uniform(.20,.28)
    yy,xx=np.mgrid[:16,:16];noise=rng.normal(0,.025,(16,16,16,3)).astype('float32')
    videos=[]
    for label in (0,1):
        frames=[]
        for t in range(16):
            width=base+(1 if label else -1)*amplitude*t/15 if task=='motion' else base
            inside=(abs(yy-7.5)<4)&(abs(xx-7.5)<width*7)
            color=np.array([.82,.82,.82]) if task=='motion' else (np.array([.85,.25,.25]) if label==0 else np.array([.25,.25,.85]))
            image=np.full((16,16,3),.15,dtype='float32');image[inside]=color
            frames.append(np.clip(image+noise[t],0,1))
        videos.append(np.stack(frames))
    return videos
def dataset(task,seeds):
    videos=[];labels=[]
    for seed in seeds:
        for y,video in enumerate(make_pair(seed,task)):
            videos.append(video);labels.append(y)
    return np.stack(videos),np.array(labels)
for task in ('motion','appearance'):
    train,y=dataset(task,range(70));test,truth=dataset(task,range(1000,1050))
    for spacing in (1,2):
        for count in (1,4,8,16):
            idx=np.minimum(np.arange(count)*spacing,15)
            X=train[:,idx].reshape(len(train),-1);Z=test[:,idx].reshape(len(test),-1)
            mean=X.mean(axis=0);X=X-mean;Z=Z-mean
            alpha=np.linalg.solve(X@X.T+np.eye(len(X)),y-.5);w=X.T@alpha
            prediction=(Z@w+.5>=.5).astype(int)
            print(task,'fotogramas',count,'separación',spacing,'aciertos',int((prediction==truth).sum()),'/',len(truth))

Local lab: recognizing actions in video

Compare an inflated ResNet-18 with separate spatial and temporal convolutions against VideoMAE fine-tuned on ten classes from a UCF101 subset. The first starts from image weights and uses per-channel temporal convolution initialized as identity; it is an educational factorized variant, not an exact R(2+1)D reproduction. VideoMAE starts from Kinetics-tuned weights and replaces its 400-class classifier with a ten-class one: pretraining and resolution differ, so this comparison does not isolate architecture alone. Whether pretraining data include videos related to this subset has not been checked, so local group splitting does not rule out all prior contamination. Reserve 300 clips for training, 30 for checkpoint selection, and 75 for test; same-class groups are not shared across splits.

The first block downloads the UCF101 subset and VideoMAE weights at pinned revisions, checks SHA-256, and verifies all 405 extracted videos. The subset card declares Apache-2.0, but rights for each source video have not been verified; check their conditions before redistribution. The VideoMAE card states CC BY-NC 4.0. Code requires Python 3.12, huggingface_hub, numpy, torch, torchvision, transformers and av. The recorded run uses NumPy 2.5.4, PyTorch 2.11.0+cu128, torchvision 0.26.0+cu128, Transformers 5.23.0, PyAV 15.1.0 and huggingface_hub 2.4.0. ResNet-18 weights are obtained from torchvision the first time. If resources already exist, ORYON_UCF_ARCHIVE, ORYON_UCF_ROOT and ORYON_VIDEOMAE_ROOT specify their paths and avoid downloading again.

[ ]Preparing and verifying dataLocal GPU
"""Descarga fijada y verificación de UCF101 subset y VideoMAE."""
import hashlib,os,tarfile
from pathlib import Path
from huggingface_hub import hf_hub_download,snapshot_download

def digest(stream):return hashlib.file_digest(stream,'sha256').hexdigest()
root=Path(os.environ.get('ORYON_UCF_ROOT','oryon-ucf101/UCF101_subset')).resolve()
if root.name!='UCF101_subset':raise ValueError('ORYON_UCF_ROOT debe terminar en UCF101_subset')
model=Path(os.environ.get('ORYON_VIDEOMAE_ROOT','oryon-videomae-kinetics')).resolve()
archive=os.environ.get('ORYON_UCF_ARCHIVE')
if archive is None:
 archive=hf_hub_download('sayakpaul/ucf101-subset','UCF101_subset.tar.gz',repo_type='dataset',revision='b9984b8d2a95e4a1879e1b071e9433858d0bc24a')
archive=Path(archive)
with archive.open('rb') as f:assert digest(f)=='e9fcc76af48d320be88c5265f2e0576ecd615956976f6ce4742fdf2b042b71eb'
if not (model/'model.safetensors').exists() or not (model/'config.json').exists():
 snapshot_download('MCG-NJU/videomae-base-finetuned-kinetics',revision='488eb9a0565f257b32866000305c8178965eb9f6',local_dir=model,allow_patterns=['config.json','model.safetensors'])
with (model/'model.safetensors').open('rb') as f:assert digest(f)=='065cfde56f97671da4d196e1a3a6d3cf9304dcad92eb671e3632a6c6cdd04f73'
with tarfile.open(archive,'r:*') as tar:
 members=tar.getmembers()
 for item in members:
  path=Path(item.name)
  if path.is_absolute() or not path.parts or path.parts[0]!='UCF101_subset' or '..' in path.parts or not (item.isfile() or item.isdir()):
   raise ValueError('Miembro de archivo inesperado: '+item.name)
 if not root.exists():
  root.parent.mkdir(parents=True,exist_ok=True);tar.extractall(root.parent,filter='data')
 files=[m for m in members if m.isfile()]
 if len(files)!=405:raise ValueError('Cantidad inesperada de vídeos')
 for item in files:
  target=root.parent/Path(item.name)
  with tar.extractfile(item) as original,target.open('rb') as copy:
   if digest(original)!=digest(copy):raise ValueError('Vídeo extraído distinto: '+item.name)
print('Verificados',len(files),'vídeos y pesos VideoMAE; datos',root,'modelo',model)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second block trains three epochs per configuration: factorized ResNet with 1, 4 and 8 frames, and VideoMAE with 8 and 16. It selects on validation and evaluates once on test; it records predictions, time, and CUDA memory. Optimizer and generator states are saved after each epoch; enable ORYON_VIDEO_RESUME=1 to resume under the same contract. The measured run uses ORYON_VIDEO_DEVICE=cuda, ORYON_VIDEO_BF16=1, ORYON_VIDEO_BATCH=1, ORYON_VIDEO_ACCUM=2 and ORYON_THREADS=1. Effective batch size two accumulates gradients, but BatchNorm updates statistics on each microbatch of one; it is not identical to a physical batch of two. Changing epoch count or configurations produces a different experiment.

[ ]Training and evaluating video modelsLocal GPU
"""Comparación real de vídeo; requiere torch, torchvision, transformers y PyAV."""
import os,sys,json,time,random,hashlib
from pathlib import Path
from functools import lru_cache
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset,DataLoader
import av
from torchvision.models import resnet18,ResNet18_Weights
from transformers import VideoMAEForVideoClassification,VideoMAEConfig

DATA=Path(os.environ.get('ORYON_UCF_ROOT','oryon-ucf101/UCF101_subset'))
MODEL=Path(os.environ.get('ORYON_VIDEOMAE_ROOT','oryon-videomae-kinetics'))
OUT=Path(os.environ.get('ORYON_L30_OUT','oryon-l30-results'));OUT.mkdir(parents=True,exist_ok=True)
torch.set_num_threads(int(os.environ.get('ORYON_THREADS','1')));torch.manual_seed(30);np.random.seed(30);random.seed(30)
device=torch.device(os.environ.get('ORYON_VIDEO_DEVICE','cuda' if torch.cuda.is_available() else 'cpu'))
if device.type=='cuda' and not torch.cuda.is_available():raise RuntimeError('CUDA no disponible')
use_amp=os.environ.get('ORYON_VIDEO_BF16','0')=='1'
if use_amp and (device.type!='cuda' or not torch.cuda.is_bf16_supported()):raise ValueError('bf16 solicitado sin CUDA compatible')
labels=sorted(p.name for p in (DATA/'train').iterdir() if p.is_dir());ids={name:i for i,name in enumerate(labels)}

def file_digest(path):
    with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
@lru_cache(maxsize=1)
def data_fingerprint():
    h=hashlib.sha256()
    for split in ('train','val','test'):
        for p in sorted((DATA/split).glob('*/*.avi')):
            h.update(p.relative_to(DATA).as_posix().encode());h.update(bytes.fromhex(file_digest(p)))
    return h.hexdigest()
@lru_cache(maxsize=2)
def model_fingerprint(family):
    if family=='videomae':
        h=hashlib.sha256();h.update(bytes.fromhex(file_digest(MODEL/'config.json')));h.update(bytes.fromhex(file_digest(MODEL/'model.safetensors')));return h.hexdigest()
    return file_digest(Path(torch.hub.get_dir())/'checkpoints'/'resnet18-f37072fd.pth')

class Clips(Dataset):
    def __init__(self,split,nframes,size):
        self.items=sorted((p,ids[p.parent.name]) for p in (DATA/split).glob('*/*.avi'));self.nframes=nframes;self.size=size
    def __len__(self):return len(self.items)
    def __getitem__(self,i):
        path,label=self.items[i]
        with av.open(str(path)) as container:
            frames=[frame.to_ndarray(format='rgb24') for frame in container.decode(video=0)]
        if not frames:raise ValueError(f'vídeo vacío: {path}')
        sample=np.stack([frames[j] for j in np.linspace(0,len(frames)-1,self.nframes).round().astype(int)])
        x=torch.from_numpy(sample).permute(0,3,1,2).float()/255
        height,width=x.shape[-2:];factor=self.size/min(height,width)
        x=torch.nn.functional.interpolate(x,size=(round(height*factor),round(width*factor)),mode='bilinear',align_corners=False)
        top=(x.shape[-2]-self.size)//2;left=(x.shape[-1]-self.size)//2
        x=x[:,:,top:top+self.size,left:left+self.size]
        x=(x-torch.tensor([.485,.456,.406])[None,:,None,None])/torch.tensor([.229,.224,.225])[None,:,None,None]
        return x,label

class Factorized(nn.Module):
    def __init__(self,conv):
        super().__init__();self.spatial=nn.Conv3d(conv.in_channels,conv.out_channels,(1,*conv.kernel_size),
             stride=(1,*conv.stride),padding=(0,*conv.padding),dilation=(1,*conv.dilation),groups=conv.groups,bias=conv.bias is not None)
        self.temporal=nn.Conv3d(conv.out_channels,conv.out_channels,(3,1,1),padding=(1,0,0),groups=conv.out_channels,bias=False)
        with torch.no_grad():
            self.spatial.weight.copy_(conv.weight.unsqueeze(2))
            if conv.bias is not None:self.spatial.bias.copy_(conv.bias)
            self.temporal.weight.zero_();self.temporal.weight[:,:,1,0,0]=1
    def forward(self,x):return self.temporal(self.spatial(x))

def inflate(module):
    for name,child in list(module.named_children()):
        if isinstance(child,nn.Conv2d):replacement=Factorized(child)
        elif isinstance(child,nn.BatchNorm2d):
            replacement=nn.BatchNorm3d(child.num_features,eps=child.eps,momentum=child.momentum,affine=child.affine,track_running_stats=child.track_running_stats)
            replacement.load_state_dict(child.state_dict())
        elif isinstance(child,nn.MaxPool2d):replacement=nn.MaxPool3d((1,3,3),stride=(1,2,2),padding=(0,1,1))
        elif isinstance(child,nn.AdaptiveAvgPool2d):replacement=nn.AdaptiveAvgPool3d((1,1,1))
        else:inflate(child);continue
        setattr(module,name,replacement)
    return module

class Inflated(nn.Module):
    def __init__(self):
        super().__init__();self.net=inflate(resnet18(weights=ResNet18_Weights.IMAGENET1K_V1));self.net.fc=nn.Linear(512,len(labels))
    def forward(self,x):return self.net(x.permute(0,2,1,3,4))

class VideoMAE(nn.Module):
    def __init__(self,nframes):
        super().__init__();config=VideoMAEConfig.from_pretrained(MODEL,local_files_only=True)
        config.num_frames=nframes;config.num_labels=len(labels);config.id2label={i:n for i,n in enumerate(labels)};config.label2id=ids
        self.net=VideoMAEForVideoClassification.from_pretrained(MODEL,config=config,ignore_mismatched_sizes=True,local_files_only=True)
    def forward(self,x):return self.net(pixel_values=x).logits

def run(family,nframes,epochs=3):
    size=112 if family=='inflated' else 224;model=(Inflated() if family=='inflated' else VideoMAE(nframes)).to(device)
    assert next(model.parameters()).device.type==device.type
    print('dispositivo real',next(model.parameters()).device,'bf16 autocast',use_amp,flush=True)
    batch=int(os.environ.get('ORYON_VIDEO_BATCH','2'));accum=int(os.environ.get('ORYON_VIDEO_ACCUM','1'))
    if batch<1 or accum<1:raise ValueError('Lote y acumulación deben ser positivos')
    loaders={s:DataLoader(Clips(s,nframes,size),batch_size=batch,shuffle=s=='train',num_workers=0) for s in ('train','val','test')}
    optimizer=torch.optim.AdamW(model.parameters(),lr=1e-4,weight_decay=.01);best=-1;checkpoint=OUT/f'{family}-{nframes}.pt'
    resume=OUT/f'{family}-{nframes}.resume.pt';completed=0;elapsed_before=0.;old_allocated=old_reserved=0
    contract={'family':family,'frames':nframes,'size':size,'epochs':epochs,'batch':batch,'accumulate':accum,'seed':30,
              'bf16_autocast':use_amp,'device_type':device.type,'torch':torch.__version__,
              'data_fingerprint':data_fingerprint(),'backbone_fingerprint':model_fingerprint(family)}
    if os.environ.get('ORYON_VIDEO_RESUME')=='1' and resume.exists():
        state=torch.load(resume,map_location='cpu',weights_only=False)
        if state['contract']!=contract:raise ValueError('Contrato de reanudación incompatible')
        model.load_state_dict(state['model']);optimizer.load_state_dict(state['optimizer'])
        completed=state['epoch'];best=state['best'];elapsed_before=state['elapsed'];old_allocated=state['peak_allocated'];old_reserved=state['peak_reserved']
        random.setstate(state['python_rng']);np.random.set_state(state['numpy_rng']);torch.set_rng_state(state['torch_rng'])
        if device.type=='cuda':torch.cuda.set_rng_state(state['cuda_rng'],device)
        if completed>0 and not checkpoint.exists():raise ValueError('Falta el mejor checkpoint anterior')
        print('Reanudada época',completed,flush=True)
    start=time.perf_counter()
    if device.type=='cuda':torch.cuda.reset_peak_memory_stats()
    for epoch in range(completed,epochs):
        model.train();losses=[];optimizer.zero_grad(set_to_none=True);n_batches=len(loaders['train'])
        for i,(x,y) in enumerate(loaders['train']):
            x=x.to(device);y=y.to(device)
            with torch.autocast(device_type='cuda',dtype=torch.bfloat16,enabled=use_amp):loss=nn.functional.cross_entropy(model(x),y)
            group_start=(i//accum)*accum*batch;group_examples=min(accum*batch,len(loaders['train'].dataset)-group_start)
            (loss*(len(y)/group_examples)).backward();losses.append(float(loss.detach()))
            if (i+1)%accum==0 or i+1==n_batches:optimizer.step();optimizer.zero_grad(set_to_none=True)
        val=accuracy(model,loaders['val']);print(family,nframes,'época',epoch+1,'loss',np.mean(losses),'val',val,flush=True)
        if val['correct']>best:
            best=val['correct'];temp_checkpoint=checkpoint.with_suffix('.pt.tmp');torch.save(model.state_dict(),temp_checkpoint);temp_checkpoint.replace(checkpoint)
        peak_allocated=max(old_allocated,torch.cuda.max_memory_allocated() if device.type=='cuda' else 0)
        peak_reserved=max(old_reserved,torch.cuda.max_memory_reserved() if device.type=='cuda' else 0)
        state={'contract':contract,'epoch':epoch+1,'best':best,'model':model.state_dict(),'optimizer':optimizer.state_dict(),
               'python_rng':random.getstate(),'numpy_rng':np.random.get_state(),'torch_rng':torch.get_rng_state(),
               'cuda_rng':torch.cuda.get_rng_state(device) if device.type=='cuda' else None,
               'elapsed':elapsed_before+time.perf_counter()-start,'peak_allocated':peak_allocated,'peak_reserved':peak_reserved}
        temp_resume=resume.with_suffix('.pt.tmp');torch.save(state,temp_resume);temp_resume.replace(resume)
        old_allocated,old_reserved=peak_allocated,peak_reserved
    model.load_state_dict(torch.load(checkpoint,map_location=device,weights_only=True));test=accuracy(model,loaders['test'])
    props=torch.cuda.get_device_properties(device) if device.type=='cuda' else None
    return {'family':family,'frames':nframes,'resolution':size,'seed':30,'epochs':epochs,'batch':batch,'accumulate':accum,'best_val_correct':best,'test':test,
            'train_val_test_seconds':elapsed_before+time.perf_counter()-start,'device':str(device),'bf16_autocast':use_amp,'gpu_name':props.name if props else None,
            'gpu_total_bytes':props.total_memory if props else None,
            'peak_gpu_allocated_bytes':max(old_allocated,torch.cuda.max_memory_allocated()) if props else None,
            'peak_gpu_reserved_bytes':max(old_reserved,torch.cuda.max_memory_reserved()) if props else None}
@torch.no_grad()
def accuracy(model,loader):
    model.eval();correct=total=0;records=[]
    for x,y in loader:
        with torch.autocast(device_type='cuda',dtype=torch.bfloat16,enabled=use_amp):logits=model(x.to(device))
        pred=logits.argmax(-1).cpu();correct+=int((pred==y).sum());total+=len(y)
        records.extend(zip(y.tolist(),pred.tolist()))
    return {'correct':correct,'total':total,'accuracy':correct/total,'pairs':records,
            'files':[p.name for p,_ in loader.dataset.items]}

if __name__=='__main__':
    configs=[('inflated',1),('inflated',4),('inflated',8),('videomae',8),('videomae',16)]
    results=[]
    for family,frames in configs:
        results.append(run(family,frames,int(os.environ.get('ORYON_VIDEO_EPOCHS','3'))))
        (OUT/'results.json').write_text(json.dumps({'labels':labels,'results':results},indent=2),encoding='utf8')
        if device.type=='cuda':torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
InteractiveNatural video: test results
  • Test accuracy
0%25%50%75%100%8/751 frames8/754 frames16/758 frames

Checkpoint selected with 30 validation clips. Three epochs, one training seed and held-out groups; time accumulates training and evaluation, excluding loading and repeated interrupted work; it is not per-inference latency.

1 frames: validation 6/30 · time 101 s · peak reserved 0.26 GiB
4 frames: validation 3/30 · time 139 s · peak reserved 0.26 GiB
8 frames: validation 5/30 · time 146 s · peak reserved 0.28 GiB
Model
1 frames8/75
4 frames8/75
8 frames16/75
In-house results on the same 75 held-out UCF101 subset videos; change models. Three epochs and one training seed per configuration, with different initial weights and resolution.

On the 12 GiB RTX 3060, factorized ResNet classified 8/75, 8/75 and 16/75 videos correctly with 1, 4 and 8 frames; VideoMAE got 74/75 and 72/75 with 8 and 16. For the latter, three videos were correct only for the eight-frame version and one only for 16: the paired two-sided exact binomial test gives p=0.625p=0.625. It proves neither equality nor a general advantage for more or fewer frames. The 16-frame model reached a PyTorch-recorded CUDA reserved-memory peak of about 2.24 GiB; cost depends on batch, precision, and hardware. Accumulated times exclude initial loading and partial work repeated after interruption. Per-video intervals assume independence and may be optimistic because clips share groups. Each variant trained once: results do not measure variation across initializations or separate architecture from resolution and pretraining. Prior data may include videos related to this subset.

Exercises

Numeric
With 16 frames of 224×224, 16×16 patches and 2-frame tubelets, how many space–time tokens are there without a special token?
Proof
Prove: Derive the flow equation and Lucas–Kanade system.
0
Assume constant brightness, small displacement and differentiable intensity in a window with common velocity.

Step 1 of 3. What does first-order expansion give?

Quiz
Why can a tube mask make video reconstruction harder?
Quiz
To detect an arm releasing an object with 20 ms per inference, what procedure is defensible?
Code
Implement divided_space_time_attention(x,T,N) for x of shape (T,N,D). Use softmax attention without projections with Q=K=V, first over T for each position N and then over N for each instant. Return (T,N,D).
def divided_space_time_attention(x,T,N):
  pass
Shift+Enter to run
Key idea
Video adds motion and temporal redundancy: choose representation and sampling with explicit costs and evaluate whether the task actually needs time.