LLM Developer DocsLLM Docs

Loading the search index ...

↑ ↓ move, Enter open, Esc close

GitHub

gradcheck.py

Finite-difference gradient checker, used only by tests

Where it fits

0 of 3 functions, classes and methods here are reachable from train.main, and 0 from talk.main. Only tests use this file.

Imports and used by

Imports from this repository
None
Other imports
numpy
Imported by
tests/test_gradcheck.py
Used by, in the pipeline
No file
Used by, in tests
tests/test_gradcheck.py

Mathematics used

ConceptWhat this file doesLinesStatus
Central differenceComputes it, Writes it in place12, 31Implemented
Relative errorComputes it, Calls it17, 31Implemented
Checking every parameterComputes it31, 32Implemented

Functions and constants

Source

gradcheck.py33 linesGitHub: gradcheck.py
import numpy as npdef numerical_grad(f, x, h = 1e-5):    g = np.zeros_like(x)    for idx in np.ndindex(*x.shape):        old = x[idx]        x[idx] = old + h        fp = f(x)        x[idx] = old - h        fm = f(x)        x[idx] = old        g[idx] = (fp - fm) / (2 * h)    return gdef relative_error(a, b, eps = 1e-12):    return abs(a - b) / max(abs(a), abs(b), eps)def check_params(loss_fn, params, grads, rng, samples_per_param = 5, h = 1e-5):    worst: dict[str, float] = {}    for name, W in params.items():        w = 0.0        for _ in range(samples_per_param):            idx = tuple(int(rng.integers(s)) for s in W.shape)            old = W[idx]            W[idx] = old + h            fp = loss_fn(params)            W[idx] = old - h            fm = loss_fn(params)            W[idx] = old            w = max(w, relative_error(grads[name][idx], (fp - fm) / (2 * h)))        worst[name] = w    return worst