foundation16 min studyLesson 3 in Engineering

Memory, locality, and the shape of data

Estimate payloads, distinguish virtual from physical memory, and understand why access patterns affect throughput.

On this page

What you’ll understand

  • Calculate a tensor's raw memory footprint.
  • Distinguish an address-space model from physical memory usage.
  • Explain how layout and reuse influence data movement.

A model can fit mathematically on a page and fail immediately when its tensors are allocated. Memory engineering connects the shape of data to the machines that move and store it. Counting bytes is the first step. Understanding ownership, temporary copies, and the order in which those bytes are touched is what makes the estimate useful.

Payload is a floor, not a complete budget

A dense rectangular array has a simple element count: multiply its dimensions. Multiply again by bytes per element to obtain its raw payload. This estimate excludes object headers, alignment, sparse indices, and runtime bookkeeping. In training, weights are only one category: activations, gradients, optimizer state, input batches, communication buffers, and temporary workspaces can all consume memory. Count their lifetimes as well as their maximum individual sizes.

Two objects with the same logical contents need not use the same layout. An array of packed numbers differs from a collection of references to separately allocated objects. A view can reuse existing storage while a copy allocates new storage. An apparently harmless conversion or transpose may create a copy in one library and a view in another. Check the actual operation's contract before assuming either behavior.

Mpayload=(∏j=1knj)sM_{\rm payload}=\left(\prod_{j=1}^{k}n_j\right)s
The dimension lengths n_j count elements along each axis, and s is bytes per element. The product assumes a dense packed representation and excludes all overhead and additional live buffers.↔ Scroll wide equations horizontally.

Addresses are not a direct map of installed RAM

Virtual memory gives a process an address space whose mappings are managed by the operating system. Physical pages can back those mappings, and pages may also be shared or backed by files. Reserving a large address range is therefore different from actively occupying the same amount of physical RAM. Metrics with similar names can count different things; compare resident usage, virtual size, and allocation reports only after understanding their definitions.

Caches and the memory hierarchy exploit reuse and nearby access, but exact sizes and policies depend on hardware. Reading contiguous elements often gives the system more opportunities to use fetched data than following widely scattered references. This is a mechanism to investigate, not a promise that every contiguous program is faster. Arithmetic intensity, vectorization, prefetching, parallel access, and working-set size also change the outcome.

tmove≥DBt_{\rm move}\geq\frac{D}{B}
Moving D bytes through a bottleneck with sustained bandwidth B bytes per second requires at least D/B seconds under this idealized bound. It excludes startup latency and assumes no compression or reuse eliminates transfers.↔ Scroll wide equations horizontally.

Optimize live data and movement together

A working set is the data actively needed over a period of execution. Processing in blocks can reuse a smaller working set before moving on. Reusing a buffer can reduce repeated allocations, while careless reuse can overwrite data still needed elsewhere. Ownership and lifetime rules therefore belong alongside performance reasoning: know which component may mutate a buffer and when readers have finished with it.

Before changing layout, measure the actual bottleneck. A program waiting on a remote database will not necessarily benefit from a packed local array. The lab offers a related capacity example: a dense all-pairs table has a quadratic element count. Interpret positive xx as a normalized item count and aa as a normalized per-entry byte cost in y=ax2y=ax^2. Move xx to observe how a doubled item count multiplies payload. It is not a cache or bandwidth simulator. Compare actual throughput and peak live memory separately when changing a real layout.

A batch and its temporary copy

A batch contains 64 images, each 224 × 224 pixels with three channels, stored as four-byte values. A preprocessing step temporarily retains a second full copy.

  1. Multiply dimensions: 64 × 224 × 224 × 3 = 9,633,792 elements. Four bytes per element gives 38,535,168 bytes, approximately 36.75 MiB for one payload.

  2. While the original and copied arrays coexist, their combined element payload is 77,070,336 bytes, approximately 73.5 MiB. A later release does not erase this peak.

  3. If the bottleneck can sustain 10 billion bytes per second, transferring one payload has an idealized lower bound near 3.85 milliseconds. Real elapsed time can be larger, and the implementation may move the data more than once.

The result

Budget overlapping lifetimes and actual transfer counts. A single-array estimate misses a factor of two in this deliberately simple example.

Explore the model

Interactive lab

Interactive lab · function

The payload of an all-pairs table

Explore y=ax² with positive normalized item count x and coefficient a representing normalized bytes per table entry. The model illustrates a dense square table's payload growth; it omits cache behavior, allocation, and transfer time.

The payload of an all-pairs tableThis 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 dense all-pairs representation grows quadratically even before copies and metadata are counted.

Check your understanding

A process reserves 8 GiB of virtual address space. Which conclusion is justified?

Try it yourself

A dense matrix has 2,048 rows and 1,024 columns of two-byte elements. What is its raw payload, and what happens if three equal copies coexist?

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

Give me a hint

Calculate one matrix first, then account for simultaneous lifetimes.

Compare with the solution

The matrix contains 2,097,152 elements and 4,194,304 bytes, exactly 4 MiB. Three simultaneous copies have 12 MiB of element payload, before metadata and allocator overhead. Sequentially reusing one allocation could avoid that tripling only if the algorithm's ownership and lifetime requirements permit it.

Take it with you

  • Dense payload equals element count times element size.
  • Virtual address space and resident physical memory answer different questions.
  • Layout, reuse, and overlapping lifetimes determine practical memory cost.

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.