We move from CPU ndarray::Array2 (day 10) to GPU tensors — same idea, different hardware
We use Burn — a Rust framework that looks like PyTorch and runs on CUDA, wgpu, Metal, or the CPU
We connect today’s material back to day 8 traits — Backend is “just” a trait, and one function works on every device
How CPU and GPU share the work — two memory pools
CPU and GPU live in separate memory pools; every tensor must be copied across the PCIe bus to cross from one to the other.
The host (your laptop / workstation CPU) and the device (GPU) each have their own memory. They talk over the PCIe bus [the wire connecting CPU and GPU; tens of GB/s, much slower than each side’s local RAM], which is the bottleneck.
One GPU operation, end to end
Every GPU call is a sequence of host-setup → upload → kernel → download → host-read; for small problems the transfers dominate, for big problems the kernel dominates.
Tensor libraries (Burn, PyTorch, JAX) hide the upload and download — but only when both operands already live on the device. Two rules of thumb:
Build tensors on the device once; keep them there.
Vectorise — one big kernel beats many small ones because each kernel pays the launch overhead.
CPU vs GPU — different shapes of fast
CPU
GPU
Cores
~10
~10 000 arithmetic units
Good at
irregular control flow, system calls
the same op applied to lots of numbers
Latency per op
~1 ns
~µs (kernel launch overhead)
Throughput
~10² GFLOPS
~10⁴ GFLOPS
Coding style
loops, branches
whole-tensor expressions
For a 10 000 × 10 000 matrix multiply: laptop CPU ~5 s, mid-range GPU ~50 ms. The crossover is the moment your problem is large enough to amortise the kernel-launch cost.
Where bioinformatics meets the GPU
Single-cell PCA / UMAP — [cells × genes] matrices with n up to millions
PWM scanning across a genome — 1-D convolution of one-hot DNA against motif weights
Sequence neural networks — DeepBind, Basenji, Enformer; all built from conv layers
Variant-effect models, AlphaFold-style pipelines — large transformers / attention on protein sequences
Embedding search — vector databases for similar reads / cells / proteins
Every one of these reduces to a handful of tensor operations done at scale.
What is a tensor
A tensor [an N-dimensional array of numbers, with a known shape and a device it lives on] is the GPU-aware generalisation of ndarray::Array2. Element-wise addition and the matrix-vector product are the workhorse operations:
let x: Tensor<B,2>=...;// ^ ^^// | rank D — number of dimensions (2 = matrix)// backend B — which device + element type
Tensor<NdArray, 1> — CPU vector
Tensor<NdArray, 2> — CPU matrix
Tensor<Wgpu, 3> — GPU 3-D tensor [N, C, L]
Tensor<Autodiff<NdArray>, 2> — CPU matrix with gradient tracking
One generic type, four very different runtime objects. Generic code only sees Tensor<B, D>.
Quick quiz — reading the type
For each signature below, say (a) which device the tensor lives on, and (b) what its rank is — i.e., how many axes it has.
let a: Tensor<NdArray,2>=...;let b: Tensor<Wgpu,3>=...;let c: Tensor<Autodiff<NdArray>,1>=...;let d: Tensor<Cuda,4>=...;
Answers: a) CPU, rank 2 (matrix) b) GPU via WebGPU, rank 3 c) CPU with gradient tracking, rank 1 (vector) d) NVIDIA GPU, rank 4 ([N, C, H, W] is the typical 4-D shape).
Bonus: what would the signature of “a CUDA tensor of one-hot DNA in shape [N, 4, L]” be?
→ Tensor<Cuda, 3> — the channel count 4 is a runtime property of the shape, not part of the type. The type only records the rank, never the sizes.
The Backend trait — yesterday’s lesson, today’s tool
standardise works on NdArray (CPU), Wgpu (GPU), Cuda (GPU), Autodiff<NdArray> (gradients) — without one line changing.
What “dims” mean — a picture
A vector is rank 1 (one axis). A matrix is rank 2 (two axes, one stack of rows). A 3-D tensor is rank 3 (a stack of matrices). dims is the array of sizes; D in Tensor<B, D> is just how many entries that array has.
Rank\(D\) = how many axes the tensor has. Lives in the type: Tensor<B, D>.
dims = how big each axis is. Lives in the value: tensor.dims() returns [usize; D].
Shape — the most important metadata
zeros allocates a fresh tensor of the requested shape; swap_dims and reshape change only the metadata, not the underlying data buffer.
Every tensor has a shape [the tuple of sizes along each axis]. Most bugs are shape bugs.
let x: Tensor<B,3>=Tensor::zeros([32,4,100],&device);// [N, C, L]println!("{:?}", x.dims());// [32, 4, 100]let y = x.swap_dims(1,2);// [32, 100, 4]let z = y.reshape([32*100,4]);// [3200, 4]
A size-1 axis on one operand is virtually stretched to match the other operand; no memory is copied.
Two tensors of nearly-the-same shape can be combined; size-1 axes are stretched.
let a: Tensor<B,2>=Tensor::ones([5,3],&device);let b: Tensor<B,2>=Tensor::ones([1,3],&device);let c = a + b;// shape [5, 3]
a = torch.ones(5, 3)b = torch.ones(1, 3)c = a + b # shape (5, 3)
Rule: align from the right; each axis must either match or be 1. The size-1 axis is repeated without copying.
Reductions
A reduction collapses one or more axes into a smaller tensor: sum collapses everything, sum_dim(k) collapses axis k, mean_dim(k) does the same with a mean.
Collapse one or more axes to a scalar or smaller tensor.
total = x.sum()row_sum = x.sum(dim=1, keepdim=True)col_mean = x.mean(dim=0, keepdim=True)
GC content per sequence, average expression per gene, k-mer counts — every reduction in a bioinformatics pipeline is one of these.
No for-loops — the GPU mental shift
A loop of N tiny kernels each pays a launch cost; one whole-tensor op runs N elements in parallel under a single kernel launch.
// BAD: launches a kernel per element.letmut x =Tensor::<B,1>::zeros([1_000_000],&device);for i in0..1_000_000{ x = x.slice_assign([i..i+1], scalar);}// GOOD: one allocation, one kernel.let x =Tensor::<B,1>::from_floats(vec![scalar;1_000_000],&device);
# Same shift in Python — for-loop bad, vectorised op good.x = torch.full((1_000_000,), scalar)
One-hot encoding DNA — example
Each base becomes a column of the [4, L] one-hot block: A → row 0, C → row 1, G → row 2, T → row 3. Column sum is 1 everywhere.
Inserting a size-1 axis lets [N, 1, D] and [1, N, D] broadcast to a virtual [N, N, D] cube of differences; squaring, summing axis 2, and sqrt collapses it to the [N, N] distance matrix.
Pairwise Euclidean distance between \(N\) samples each of dimension \(D\):
Day 10 used ndarray for dense matrices but stopped before decompositions like SVD. For full linear algebra on the CPU we reach for nalgebra — pure Rust, no LAPACK build dependency.
usenalgebra::DMatrix;letmut m =DMatrix::from_row_slice(n_samples, n_genes,&data);// centre each columnfor j in0..n_genes {let mean:f64= m.column(j).mean(); m.column_mut(j).iter_mut().for_each(|v|*v -= mean);}let svd = m.svd(true,true);let pcs = svd.u.unwrap() *DMatrix::from_diagonal(&svd.singular_values);
from sklearn.decomposition import PCApcs = PCA(n_components=k).fit_transform(expression)
PCA is the singular value decomposition of the centred data matrix:
Sliding a PWM (a [4, w] weight matrix) along one-hot DNA gives a score at every valid starting position. Score 4 (perfect match) sits exactly where GATA occurs.
A motif PWM [position weight matrix — a [4, w] matrix of log-odds scores, one column per position in the motif] scanned along DNA is exactly a 1-D convolution.
For one input sequence (one-hot encoded as \(x \in \{0,1\}^{4 \times L}\)), one motif (kernel \(w \in \mathbb{R}^{4 \times W}\)), and a learned scalar bias \(b\):
import torch.nn as nnconv = nn.Conv1d(in_channels=4, out_channels=n_motifs, kernel_size=motif_width, bias=True)scores = conv(one_hot_dna) # [N, M, L−w+1]
The bias \(b\) acts as a learned threshold: positive bias shifts every score up (the motif is easy to “find”), negative bias shifts every score down (only strong matches survive ReLU).
Autodiff — gradients for free
Wrap any backend in Autodiff and the framework records every operation:
useburn::backend::{Autodiff, NdArray};type B = Autodiff<NdArray>;let x: Tensor<B,1>=Tensor::from_floats([3.0],&device).require_grad();let y = x.clone().powf_scalar(2.0);// y = x^2let grads = y.backward();let dx = x.grad(&grads).unwrap();// 6.0
x = torch.tensor([3.0], requires_grad=True)y = x **2y.backward()print(x.grad) # tensor([6.])
Behind the scenes, Autodiff builds the computation graph [a DAG of tensor operations recorded during the forward pass; .backward() walks it in reverse] and applies the chain rule. For a scalar loss \(\mathcal{L}\) that flows through a chain of tensor ops \(\mathcal{L} = f_n(\dots f_2(f_1(x)) \dots)\):
In our toy example, \(y = x^2\) so \(\partial y / \partial x = 2x\), evaluated at \(x = 3\) gives \(6\).
A neural network is a Module
PromoterNet is Conv1d → ReLU → global-max-pool → Linear; the learnable parameters live in Conv1d (one filter per motif, with bias) and Linear (per-channel weight and bias).
A Module is a struct of parameters plus a forward method.
class PromoterNet(nn.Module):def__init__(self, ...):self.conv = nn.Conv1d(4, C, w)self.fc = nn.Linear(C, 1)def forward(self, x): h =self.conv(x).relu() h, _ = h.max(dim=2)returnself.fc(h)
Training loop — what it looks like
The training loop in one picture: data batch → forward → loss → backward → gradients → optim.step → updated model → repeat.
letmut model: PromoterNet<B>=PromoterNet::init(&device);letmut optim =AdamConfig::new().init();for (x, y) in batches {let logits = model.forward(x);let loss = binary_cross_entropy(logits, y);let grads = loss.backward();let grads =GradientsParams::from_grads(grads,&model); model = optim.step(LR, model, grads);}
for x, y in loader: logits = model(x) loss = F.binary_cross_entropy_with_logits(logits, y) optim.zero_grad(); loss.backward(); optim.step()
The shape of the loop is exactly the same as a PyTorch loop. Burn’s flavour is just more explicit about ownership — optim.step takes the model and returns the updated model.
Recap
A tensor is the GPU-aware Array2; its type carries both backend and rank
Backend is a trait — write <B: Backend> once, run on CPU, wgpu, CUDA, or Autodiff
Broadcasting + reductions replace for loops, on CPU and GPU alike
For non-GPU linear algebra (SVD, eigenvalues), use nalgebra
Module + Autodiff give you the standard PyTorch shape of model + training loop