research30 min studyLesson 815 in Engineering

Budget the actual patch and tubelet sequence

Count spatial-temporal tokens, dense score tensors, and masked-encoder scope without turning a simplified attention allocation into a complete video-model memory claim.

On this page

What you’ll understand

  • Count tokens for a stated no-padding tubelet convention.
  • Calculate a materialized joint-attention score allocation with units.
  • Distinguish factorized attention, masking, and fused implementations from a universal quadratic-memory rule.

Video models multiply spatial evidence by temporal evidence, so a modest increase in either axis can change the sequence budget substantially. A memory estimate needs the precise tokenization convention, batch size, head count, dtype, and attention implementation. Research results for TimeSformer or VideoMAE describe particular architectures and training procedures; they are not a license to treat every video model as one identical dense attention matrix. Start with an explicit tensor and state which allocations the calculation includes.

Count the input sequence under one declared convention

For a clip with T frames and spatial size H×W, a nonoverlapping tubelet spanning τ frames and p×p pixels produces a product of temporal and spatial grid counts when all dimensions divide exactly. State whether the model pads, drops a remainder, overlaps patches, adds class tokens, or uses multiple pathways. A frame count also needs its temporal span from the sampling manifest. Doubling frames at fixed cadence lengthens the observed span, while doubling them in a fixed span increases sampling density; those are different information changes.

TimeSformer studies attention over frame-level patches, while VideoMAE uses a video masking and tubelet representation design. This lesson's generic tubelet formula should not be read as the exact input convention of every cited architecture. Record the actual implementation and any visible-token selection before estimating costs. An experiment that changes crop size, frame count, and masking simultaneously changes several resource and information axes, making a single memory or accuracy explanation difficult to isolate.

N=TτHpWpN=\frac{T}{\tau}\frac Hp\frac Wp
N is the number of video tubelet tokens for positive integer dimensions exactly divisible by τ and p, without overlap, padding, or extra tokens. Otherwise the actual padding/drop policy changes the formula. Counts are dimensionless; this expression does not specify temporal duration or model width.↔ Scroll wide equations horizontally.

Name which attention allocation is being estimated

If full joint attention explicitly materializes one score tensor of shape [batch,heads,N,N], its storage is batch×heads×N²×bytes-per-score. Doubling N quadruples that tensor. This says nothing by itself about every activation, gradient, optimizer state, or fused kernel. An implementation that avoids materializing the complete score matrix can have a different memory footprint while still evaluating relevant attention interactions. Measure peak allocation under the actual training or inference mode.

Dividing temporal and spatial attention changes the interaction structure and its cost, rather than merely renaming the same full matrix. Masked pretraining can also run an encoder on a reduced visible-token set while a decoder and reconstruction path retain additional work. A high mask ratio therefore does not imply the whole training run becomes cheaper by the square of the visible fraction. Account for the components actually executed, including input decoding and data movement, before attributing end-to-end savings to a token count.

Mscores=B h N2 bM_{\rm scores}=B\,h\,N^2\,b
B is batch count, h attention heads, and b bytes per explicitly stored score, giving bytes M_scores. This applies to the named materialized full joint-score tensor only. Q/K/V, outputs, feed-forward activations, backward state, allocator overhead, and alternative attention implementations are excluded.↔ Scroll wide equations horizontally.

Check memory and information together

Use a small count oracle and an actual peak-memory measurement for representative maximum shapes. Test remainder dimensions and extra tokens so a formula does not silently omit a model's real sequence entries. Record whether precision casts create another copy and whether activation checkpointing changes retained state. A configuration that avoids memory exhaustion still needs a quality comparison: reducing frames or resolution can discard the evidence necessary for the task even when its allocation is perfectly understood.

The function lab isolates a quadratic scaling term in normalized units. Reset, set both coefficient a=1 and position x=1, predict value one, then Play or Step. Reset and set both a=1,x=2 for value four. Interpreting x as a token-count multiplier makes the squared growth visible, but the instrument contains no video tokens, attention heads, memory allocator, masking, or fused kernel. It validates only the stated quadratic arithmetic, leaving real-model peak memory and information sufficiency to separate checks.

Count one materialized score tensor

Use a fictional clip with T=16,H=W=224, tubelets τ=2,p=16, no padding or extra tokens, batch B=2, twelve attention heads, and two bytes per explicitly stored full joint-attention score. Count only this one score tensor.

  1. The temporal grid has 16/2=8 positions and each spatial grid has 224/16=14. Thus N=8×14×14=1,568 tokens.

  2. The score tensor stores 2×12×1568²=59,006,976 scores. At two bytes each, that is 118,013,952 bytes, or 112.546875 MiB.

  3. Doubling frames to thirty-two doubles N to 3,136 and quadruples this allocation to 450.1875 MiB. The calculation excludes every other tensor and does not apply unchanged to an implementation avoiding full score materialization.

The result

This named tensor occupies about 112.55 MiB at sixteen frames. It is a scoped allocation count, not total training memory or a measured speed prediction.

Explore the model

Interactive lab

Interactive lab · function

Inspect a normalized quadratic budget term

Fresh Reset → set both a=1,x=1 predicts value 1; Reset → set both a=1,x=2 predicts 4. Play or Step displays ax² and its analytic quantities. No video tubelets, attention allocation, fused kernel, masking, or measured peak memory is simulated.

Inspect a normalized quadratic budget termThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA quadratic term is useful only when its counted object and implementation assumptions are explicit.

Check your understanding

A video encoder uses fewer visible tokens, but reconstruction uses an additional decoder. What can be inferred from the encoder token count alone?

Try it yourself

A materialized full attention tensor has N=1,024 tokens; a separate encoder variant explicitly keeps only 128. With batch, heads, and score dtype unchanged, what is the ratio of those score-tensor sizes? What claim must be avoided?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Square the token ratio and restrict the conclusion to the specified materialized tensor.

Compare with the solution

The ratio is (128/1024)²=(1/8)²=1/64. This does not imply total training memory or elapsed time is sixty-four times smaller. The reconstruction decoder, other activations, weights, gradients, input decode, and different kernels can dominate or change independently. The claim is valid for the named score tensor under the stated explicit-materialization convention only.

Take it with you

  • Token counts require exact spatial, temporal, padding, and extra-token conventions.
  • Dense score-matrix arithmetic should identify the one allocation it measures.
  • Masking, factorization, fused attention, and quality changes require separate component evidence.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.