Changelog
All notable changes to Lucid. Keep a Changelog format.
Adds Drifting Models (arXiv 2602.04770), checked against the authors' running release: generator, MAE and ConvNeXt features, the drift loss and its gradient agree to float32 noise. Fixes a run of lucid.compile steps that trained on silently wrong gradients or losses: in-place writes on tensors the call made, no_grad regions inside a forward, dropout under a segmented step, batch-norm statistics, compiled contiguous, and traced Functions inside a traced backward. lucid.set_grad_enabled is a context manager and decorator, lucid-audit --models verifies the zoo on both Metal and CPU, and the engine ABI is 46.
Added
lucid.peft/lucid.quantization: add QLoRA support —QuantizedMatmulBackwardin_C.enginepropagatingdXgradients (includingcreate_graph=Trueandfloat16/bfloat16/float32activations) throughquantized_matmulon Metal,lora.QuantizedLinearadaptingQuantizedLinearMLX,nn.quantized.Linear, andnn.quantized.dynamic.Linearwith losslessunmerge()buffer restoration and"all-linear"discovery, andprepare_model_for_kbit_trainingsupport for quantized models (LCD-717).lucid/Tensor/linalg/signal.windows: addasarray,scalar_tensor,layout,strided,deg2rad,rad2deg,logaddexp2,sgn,fix,diag,diagflat,concatenate,split_with_sizes,unsafe_chunk,unsafe_split,constant_pad_nd,unravel_index,select_scatter,slice_scatter,diagonal_scatter,dist,gradient,linalg.cholesky_inverse,linalg.lu_unpack,Tensor.{mH,is_cpu,is_meta,layout,ndimension,nelement,sum_to_size,fill_diagonal_,polygamma,t_,transpose_,swapaxes_,swapdims_,squeeze_,unsqueeze_,exponential_,cauchy_,geometric_,log_normal_,random_}, andlayout=/requires_grad=keyword arguments on all 12signal.windowsfunctions (LCD-685).lucid.peft:SwinConverter,CLIPConverter, andDETRConverteradapter-file converters supporting both release-4 and release-5 reference module layouts, fusing separatequery/key/value(q_proj/k_proj/v_proj) andout_proj(o_proj) projections into the zoo'sqkvnn.Linearandnn.MultiheadAttentionmodules (LCD-830).- add post-accumulate hooks, node hooks/next_functions, and C++ saved_tensors_hooks
- select lucid-audit packages, the model zoo included
- verify the model zoo on Metal, as an option and on record
- add the rule registry and its audit
- let the quality gate judge from a ref (LCD-841-R2)
- judge a push to main, record a bypass (LCD-841-R2)
- add Drifting Models (arXiv 2602.04770)
- export FCNOutput and EfficientFormerOutput
- validate_model_zoo rejects unexported public names (MZ080)
- judge the ABI bump and attest the C++ at push (LCD-841-R3)
- verify the model zoo on Metal and CPU by design
Fixed
lucid.compile:make_step(segments=N)froze a value one segment stores and a later one reads (a dict, list, attribute or closure stash) and trained on the first call's value with a wrong gradient; it now runs eagerly with asegment-valuesnotice and equals eager (LCD-902).lucid.compile: a compiled function usingmasked_select,linalg.lu_factor_ex,linalg.ldl_factor_exorlinalg.householder_productreturned the first call's result for every later input with no error. These signatures now run eagerly and answer each input (LCD-836).linalg.pinvraisesLinAlgErroron an infinite matrix withmin(m, n) >= 3instead of never returning, andlinalg.lstsqreturns a NaN solution for a non-finite batch element, as the reference does, instead of raising (LCD-833).ErrorBuilder/LapackInfo/Indexing: prefix C++ errors with the public operation name (take,index_select,transpose,unfold,scatter,frombuffer,clamp,fft,tril/triu,linalg.*), omit[trace=...]unlessLUCID_ERROR_TRACEis set, format index-out-of-bounds messages with the offending index, dimension, and extent, report human-readable LAPACK convergence/factorization failures, and raiseValueErrorinstead ofRuntimeErroron invalid scalar/shape arguments across 19 ops (LCD-673, LCD-675).linalg.eigh,linalg.svd, andlinalg.pinv: raiseLinAlgErroron non-finite inputs across CPU and Metal whenmin(m, n) >= 3(svd/pinv) or when any referenced triangle entry is non-finite (eigh), and report the failing batch index on batchedeigh(LCD-674).compile/coreml: clamp bitwise shift counts (bitwise_left_shift,bitwise_right_shift) in MPSGraph to $[0, W-1]$ (masking shifts ofWor more to0on unsigned and<<, and toW - 1on arithmetic signed>>), support signed integerpow(int8/int16/int32/int64) in MPSGraph with negative-exponent error parity, and castint64powoperands toint32in Core ML MIL export (LCD-727).metal:wrap_mlx_arraybinds thread streams and evaluates in place when an op outside the dispatcher (fft,qr,eigh,scatter_add) is a thread's first MLX work;synchronize_gpuandready_buffersrelease the GIL only while waiting on a stream token after encoding (run_then_wait), closing cross-thread command-buffer deadlock windows (LCD-701)._C.engine: validateTensorImplPtrarguments at C++ entry points (cummax,cummin,ravel,sum,prod,square,cube,concatenate,concat,stack,meshgrid,einops.einsum) so passingNoneraisesTypeErrorinstead of dereferencing a null pointer (LCD-683).random_uniform: clamp floating-point uniform draws tonextafter(hi, -inf)in the target dtype precision (float16,bfloat16,float32,float64,complex64) on both CPU and Metal so the half-open interval $[lo, hi)$ never rounds up tohi(LCD-774).matmul(mm,bmm) anddot: rejectbooloperands withNotImplementedErroron CPU and Metal rather than promoting to integer accumulation (LCD-775).pad: addint8,int16, andboolkernels with saturating constant-fill conversion on CPU and Metal, and remove theint8/int16promotion workaround in pooling windows (LCD-791).cummaxandcummin: supportfloat16andbfloat16backward passes (create_graph=Falseandcreate_graph=True) on CPU and Metal (LCD-682).max_pool{1,2,3}dandadaptive_max_pool{1,2,3}d: return zero gradient (instead of routing gradient to index0) on all--infwindows, pick the firstNaNwindow index on CPU and Metal, and map constant-padded window positions to valid input indices whenreturn_indices=True(LCD-748).lucid.tensor(..., dtype=bfloat16, device="metal"): convert float64 host sequences tobfloat16bits on CPU before uploading raw uint16 words to Metal sobfloat16subnormals are preserved on M4 Max (LCD-746).count_nonzero,logical_not,logical_and,logical_or,logical_xor,cdist(..., p=0), andlinalg.vector_norm(..., ord=0): route truthiness tests through_truth_mask(astype(Bool)/ complex real-or-imag mask) so subnormal floating-point values on Metal are preserved as nonzero rather than flushed to zero bynot_equal(..., 0)(LCD-745).nn:MultiheadAttentionexposes anout_projnn.Linearview overout_proj_weight/out_proj_biasandmerge_masks(attn_mask, key_padding_mask, query),TransformerEncoderLayerandTransformerDecoderLayername their FFN/residual dropout modulesdropout/dropout1/dropout2(/dropout3),TransformerEncoderexposesuse_nested_tensor, andLPPool2dexposeskernel_sizeandstrideattributes (LCD-753).compile/quantization:fused_stepcarries outside in-place buffer writes (including QATFakeQuantizeobservers) back viarun_executable_inplaceinstead of falling back to eager;QuantizedLinearMLXpreserves input floating dtype (float16/bfloat16), moves CPU-resident packed buffers onto Metal on demand, and warns when called with arequires_grad=Trueinput;compiled_stepsupports models with unused parameters and raises clear errors on non-scalar or detached losses (LCD-724).arange/as_strided/conv{1,2,3}d/unfold/fold:_exact_int64_arangechecks the range element count before unpacking intostruct.pack,as_strided_positionsrefuses output sizes aboveINT32_MAX, andConvNd/Unfold/Foldcompute output spatial dimensions inint64_tbefore checking bounds so oversized padding or shapes raiseRuntimeError/ValueErrorcleanly (LCD-700).lucid.float_powerpromotes complex operands tocomplex128instead of dropping the imaginary part intofloat64, andlucid.expm1/lucid.sincavoid ordering comparisons (clamp) on complex inputs so higher-order derivatives (create_graph=True) work on complex tensors (LCD-698).compile_optimizer:CompiledOptimizer.state(and the wrapped optimizer's.state) is now a live read-only view over the compiled state buffers keyed byParameter, matchingstate_dict()["state"]and eagerOptimizer.state(LCD-813).lucid.diffeq.odeintandodeint_dense: support complex initial statesy0(complex64/complex128) across fixed-step and adaptive Runge–Kutta solvers (rk4,dopri5), andlucid.finfonow accepts complex dtypes and returns the underlying real component limits (LCD-817).lucid.nn:F.one_hotrejects non-integer index tensors,F.batch_norm(..., training=False)requiresrunning_meanandrunning_varto be defined,F.conv{1,2,3}d/F.conv_transpose{1,2,3}dreject weights with zero channel dimensions, andReflectionPad{1,2,3}d,ReplicationPad{1,2,3}d, andCircularPad{1,2,3}denforce batched or unbatched spatial input ranks (LCD-699).- record trace I/O for masked_select, LU, LDL, householder
- name unsafe_split's first parameter input (LCD-844)
- measure short zoo stages, type the stage for mypy --strict
- erase the zoo's live frame, say what a narrowed floor held
- lead a killed stage's failure with who killed it
- stop baselines and zoo records saying more than was checked
- keep nohup's hangup ignore, find a family's tests by class
- take the weights axis's probe out of the registry
- follow a write into the views that share its buffer
- compile: a view taken before an in-place write to its base no longer keeps the value from before the write. A compiled call that reads such a view, as an op input, as a value copied into another tensor or as its return value, now runs eagerly and matches eager. Core ML export of a function returning such a view raises ValueError instead of exporting the pre-write value. Views of batch norm running statistics and overlapping buffers written in one call also follow eager.
- build tables for the default device (LCD-849)
create_modelunderlucid.set_default_device("metal")gives a model whole on Metal. I-JEPA, V-JEPA and Stable Diffusion no longer raise on float64 at build, and Transformer, NCSN, DiT and learned-variance DDPM no longer leave a table on the CPU.- make the rule audit prove what it claims
- run eigh on the Jacobi graph svd already uses (LCD-838)
- replay MPSGraph's clone walk before compiling (LCD-838)
lucid.compileno longer hangs oneigvalshandeighof 4x4 and larger, or on full-matricessvd.eighshares the one-sided Jacobi graph withsvdandpinv, and returns up to the 16x16 limit.- Compiled graphs with deep equal-arm diamonds (
x = x * a + x * bin a loop) no longer stall in MPSGraph's clone walk. - Compiled
svd,svdvals,pinv,condandmatrix_rankno longer return wrong values for inputs with entries around 1e-7 or smaller. - A compiled
eighorsvdcall on NaN or inf input returns all NaN for that batch member, V included, and leaves the other members untouched. - keep shadow calls out of interpolate's matrix cache (LCD-858)
- compute a Metal result's shape before dispatch (LCD-850)
- answer phantom gradients without reading storage (LCD-850)
- keep embedding_bag's dtype refusal in its graph backward
- refuse what Metal cannot hold as a phantom too (LCD-850)
- answer a phantom index as an integer (LCD-850)
shadow_allocon Metal no longer raisesbad_variant_accessfromwhere,innerandtensordot, or from the ops built on them such asclamp,lgamma,cross_entropyandEmbedding(padding_idx=...).- Under
shadow_alloc,kthvalueon the CPU, the gradients ofcummax,cumminanddet, second gradients ofembedding_bagand bilinear resampling, device moves, the Metal quantized ops, andcreate_graph=Truethroughsort,msort,kthvalue,quantileandnanquantileanswer with phantoms. create_graph=Truethroughembedding_bagworks on Metal.- post-commit's CHANGELOG amend no longer folds other staged files into a path-limited commit.
- keep svd's U orthonormal, eigh finite at the limit
- Compiled
linalg.svdreturns an orthonormalU(andVhon wide input) for rank-deficient and zero matrices, where it left zero or non-orthogonal columns. - Compiled
linalg.pinvwith a smallrtolkeeps a column under 1e-12 of the largest entry;diag(1, -1e-13)came back 13 orders short. - Compiled
linalg.eighandeigvalshno longer return inf or NaN on entries past 1.7e38, and they read back an eigenvalue beside one up to 38 orders larger when the eigenvectors don't mix them. - cast after the move when .to() goes to the CPU (LCD-866)
- trace a non-materializing VJP once per demand (LCD-863)
- leave out a demand variant backward cannot trace
- match the demand for a lone region missing a cotangent
- refuse a non-materializing call no subset traces for
- refuse a call whose full variant misses an input gradient
- Compiled training steps through
svd,svdvals,matrix_norm(nuc),eighandeigvalshon a repeated or zero spectrum (identity or orthogonal weights) no longer give NaN gradients. A custom Function that does not materialize grads now gets, in a compiled step, the cotangents eager gives it for the outputs a gradient reached (Nonefor the rest). - split a max/min gradient among ties and keep NaN
- decide a write by the buffer it lands in
- compare a shared buffer's writer by view family
- close the holes the write-landing review found
- write a fused step's output into a shared buffer
- leave a held table written from constants alone
- give a held tensor back what the eager rerun did not write
- let the trace stand as the call when its rerun would read empty
- hold no result tensor past the answer handoff
- let a fused step's trace stand as the call too
- put back only a held tensor the call reads as it writes
- count a write noted twice once, and step a standing call's counters
- rerun a step whose cumulative batch norm traced without buffers
- stand for any held write where the trace can stand
- leave a compiled step's held writes to its call
- hold the zoo build budget to a measured count (LCD-851)
- give self pairs their exact distance
- prove the C++ push checks' run lines, refuse a run of skips
- prove what the attest key reads, drop autoload-off
- keep regions off a recorded backward's inner calls
- contiguous aliases in a trace as it does eager (LCD-890)
- dropout with nothing to drop is its input in a trace (LCD-890)
- carry a functional batch norm's statistics from lucid.compile
- let a segment's trace stand for a tensor it keeps
- refuse a write a compiled run cannot carry
- support unary plus, refuse it on a boolean tensor
- keep or refuse a rectangular sample_size, never square it
- Drifting promises no weights, saves only its generator
- a later ABI: none no longer excuses an earlier move
- check_weight_fit claims OK only for what it read
- an in-place op's stand-in reads the value it stands for
- an overwrite in a recording keeps its zero derivative
- a tensor put back also leaves the trace's graph
- a held tensor put back leaves the trace's graph
- what a write moves besides its values, under a trace
- a value made under no_grad is a constant to the backward
- make set_grad_enabled a scope and a decorator
- replay a segment's draws in its backward recompute
- a checkpoint reading the grad mode runs eagerly
Performance
_C.engine(Linear,ConvNd,ConvTransposeNd,LayerNorm,RMSNorm,BatchNormNd,GroupNorm,BatchNormEval,GlobalResponseNorm,Bilinear): threadneeds_input_grad(grad_mask) andkGradReadsthrough fused CPU/Metal backward kernels andapply_for_graph, skipping unneededdx/dW/dbGEMMs, convolutions, reductions, and buffer allocations (LCD-697).CpuBackend::roll,lucid.fft, andlucid.signal.windows.kaiser: replace the per-element modulo and single-elementmemcpyloop inCpuBackend::rollwith a row-wise two-slicestd::memcpyrotation (cutting(256, 4096)CPUroll/fftshiftfrom 5.1 ms to 0.049 ms), dispatch CPU power-of-two single-precision FFTs (fftn/ifftn/rfftn/irfftn) directly through Apple AcceleratevDSPwith thread-local plan/scratch caching and GCD parallelization across slices (cutting 64-point CPUfftfrom ~100 µs to 5.6 µs and(256, 4096)CPUfft/ifftfrom 2.8 ms to 0.41 ms), and use Horner evaluation and scalar denominator evaluation inlucid.i0/windows.kaiser(cuttingkaiser(64)from 420 µs to 99 µs) (LCD-769).lucid.special.log_ndtr: replacelog1pon the upper-tailerfcxcorrection (|q| <= 2.34e-3) with a short Horner Mercator series, cutting Metal first-compile time from 4.4 s to 1.6 s while preserving fullfloat32/float64accuracy (LCD-795).
Tooling
lucid-audit:--subsystemnow narrows the test-suite and doctest stages and per-file coverage checks to the selected subsystems (LCD-733).
Changed
tools/convert_weights/: the one-off weight conversion scripts are removed; only__init__.pyremains, and earlier converters stay in git ate1858082c. The YOLO parity check reads its darknet releases fromtools/_darknet_release.py, andtools/check_tvm_upstream_parity.pycarries its own key map. TVM weights are not being converted.- merge float/double vDSP plans into one template
- give fused-backward grad masks one owner (LCD-834)
- stop depending on one-off weight converters
- let the zoo stage define its own command-line options
lucid-auditis scoped by package (--<package>,--no-<package>, children included) and the model zoo is a package (--models, included by default,--no-modelsleaves it out). The zoo runs family by family on Metal by default (--zoo-device cputo change), under a memory budget taken from the machine. Baselines are written only by a run that covers everything, and only--tests-onlycan fail the line coverage floor.--subsystemand--list-subsystemsare removed (use--list-packages),--no-metalis now--cpu-only, andlucid-audit --modelsreplacestools/verify_zoo.py.F.sinusoidal_embedding,F.sinusoidal_embedding_2d,make_beta_schedule,make_sigma_schedule,diffusion_posterior_constants,flow_prior_sample,sample_point_coordsandDDPMSchedulerdefaultdevicetoNone, the current default device, instead of"cpu". Behaviour under a CPU default is unchanged.shadow_allocrefuses float64 and complex128 on Metal with theNotImplementedErrora real allocation raises.- A push to main or a
v*tag is now judged again by.githooks/pre-push(python -m tools.rules push), and a commit that skipped pre-commit carries aLucid-Bypasstrailer and a log line. - The pre-commit hook runs the rule registry's commit level on the staged blobs, so a
git add -pof part of a file underlucid/is refused.LUCID_SKIP_H4_GUARDandLUCID_SKIP_QUALITY_GATEare gone:--no-verifyis the only way past those checks, and it leaves the trailer. - The DreamerV3 learning benchmark (
TestDreamerV3ReadsTheGoal) scores every policy on a fixed 36-goal panel, treats the goal-blind ceiling as a policy, and asserts what the goal is worth to the policy (the cost of a decoy), over 3000 steps. The old test's blind ceiling was not a ceiling, and its verdict was one random draw. - A compiled step through a
_traced_backwardFunction with_materialize_grads=False(orctx.set_materialize_grads(False)) traces its backward once per set of outputs a gradient may reach; one that cannot be traced for the demands it may meet runs eagerly, and the fallback warning says why. More than 4 differentiable outputs run eagerly. - bring the family under the gate
- make the encoder and queue private
- prefix family-internal helpers with an underscore
- give Drifting's feature encoder its own module
- Drifting says guidance_scale like the zoo (LCD-891)
- drop the no_grad guards nothing reaches
- drop an assert the typed no_grad makes redundant
- _pow2 picks its path from the engine's grad mode ---