Metadata-Version: 2.4
Name: jevloss
Version: 0.1.0
Summary: NanoJev as a frozen, differentiable, per-layer loss function for any PyTorch model: write a sentence per layer, get a gradient
Author-email: Avneh <avneh@cside.dev>
License-Expression: MIT
Project-URL: Homepage, https://github.com/AvnehSBhatia/jevloss
Project-URL: NanoJev, https://github.com/TianyuCodings/NanoJev
Keywords: pytorch,loss,verifier,nanojev,interpretability,representation-learning,llm-judge
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: torch>=2.1
Requires-Dist: transformers>=4.51
Requires-Dist: safetensors>=0.4
Requires-Dist: huggingface_hub>=0.23
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# jevloss

NanoJev (a frozen Qwen3-0.6B decision model) as a **differentiable, per-layer loss for any
PyTorch model**. You write one plain sentence per layer; `jevloss` turns it into a NanoJev
question whose candidates are the batch's labels, so each layer learns to make its own
statement decodable while the main task loss (and an optional global sentence) trains the
whole network. One NanoJev forward and one NanoJev backward per step, whatever the number
of layers. Locality is exact by construction: a per-layer loss only ever writes gradients
into that layer and its decoder.

## Install

```bash
pip install jevloss                 # PyPI
uv pip install -e .                 # from a checkout
```

The NanoJev checkpoint (2.2 GB, MIT) is downloaded once by `ensure_checkpoint()` into
`~/.cache/jevloss/`, or point `NanoJev.from_checkpoint(dir)` at a local copy.

`torch` is a declared dependency but you almost always want to pick the build yourself
before installing `jevloss`:

```bash
uv pip install torch --index-url https://download.pytorch.org/whl/cpu    # CPU only (Linux)
uv pip install torch                                                     # macOS: MPS is in the default wheel
uv pip install torch --index-url https://download.pytorch.org/whl/cu124  # CUDA 12.4 (pick your version)
```

Python 3.10 or newer, torch 2.1 or newer, transformers 4.51 or newer.

## Quickstart

```python
import torch
from torch import nn
from jevloss import LayerwiseJEVLoss, NanoJev, ensure_checkpoint

LABELS = ["cat", "dog", "bird", "car", "tree", "boat"]
model = nn.Sequential(nn.Sequential(nn.Linear(24, 32), nn.GELU()),
                      nn.Sequential(nn.Linear(32, 48), nn.GELU()),
                      nn.Sequential(nn.Linear(48, len(LABELS))))
jev = NanoJev.from_checkpoint(ensure_checkpoint())            # frozen; cuda / mps / cpu
lw = LayerwiseJEVLoss(model, jev,
    objectives=["The state describes the object in the input.",   # one sentence per block
                "The state separates living things from vehicles.",
                "The state names the object's class."],
    global_objective="The final state identifies the correct label.",
    warmup_steps=50, ramp_steps=200,
    example_batch=torch.randn(2, 24))                         # materialises one decoder per block
opt = torch.optim.AdamW([*model.parameters(), *lw.parameters()], lr=1e-3)  # after example_batch=
for x, y in loader:                                           # y: class indices
    task_loss = nn.functional.cross_entropy(model(x), y)
    losses = lw.compute(labels=[LABELS[i] for i in y])        # one NanoJev forward
    lw.backward(losses, task_loss=task_loss)                  # one NanoJev backward; never task_loss.backward()
    opt.step(); opt.zero_grad()
    print({k: round(v.item(), 3) for k, v in losses.items()}, "total", losses.total.item())
```

`examples/quickstart.py` runs this on a tiny random NanoJev with no download;
`examples/real_checkpoint.py` does the same with the real checkpoint.

## Where to put it, and what to set

**Deep.** Wrap the last stage or last few blocks of the network, not early layers. Early
layers (first convs, first transformer blocks) never became judge-readable in our runs; the
last backbone stage did. One to three layers in the last third of the model is the sweet spot.

**Start from:** `ChoiceObjective(sentence, k=5, weight=5..10)` on one deep layer, a short
concrete sentence, `warmup_steps=32`, `ramp_steps=32`, `decoder=dict(num_slots=8)`, one
AdamW over `model.parameters()` plus `lw.parameters()`. Judge cross entropy below `log(k)`
with the task metric holding means it is working. Full guidance, the reasoning and the measured
numbers behind each setting are in [`docs/USAGE.md`](docs/USAGE.md).

## Read this first

1. **Objectives can be gamed.** A layer scored by a boolean sentence with an always-true
   target learns to say "true" and nothing else. Use the tiers in this order:
   `PlainObjective`/`ChoiceObjective` (candidates drawn from the batch's labels, truth slot
   reshuffled every step, grounded and contrastive) > `PairedBooleanObjective` (value swapped
   with probability `p_swap`) > `ScoreObjective` > `BooleanObjective` with a varying target.
   `compile` raises `ValueError` on the first batch if an objective has a single target
   value across two or more rows (`allow_constant=True` disables this) and warns once if the
   target entropy stays near zero for 20 steps.
2. **Recipe.** (a) `objective.sanity_check(jev, annotations, render_fn)` on ground-truth text:
   if NanoJev cannot answer the question from a plain description, no decoder will make it
   answerable from activations. (b) `warmup_steps=N`: activations are detached, only the
   decoders train. (c) `ramp_steps=M`: the per-layer weight ramps linearly into the model.
   Watch `losses.info_gain` (baseline nll minus nll): near zero means the layer carries no
   usable signal yet.
3. **Locality semantics.** `locality="params"` (default): layer `l`'s loss reaches only
   `layer_l.parameters()` and its decoder. `"block"`: also every module in the container
   between the previous selected layer and `l` (norms, adapters). `False`: an ordinary
   backward, every layer's loss flows through the whole prefix of the network. The
   `task_loss` and the global objective always reach everything.
4. **Never call `task_loss.backward()` yourself** when locality is on. Pass it to
   `lw.backward(losses, task_loss=...)`; it is folded into the single final backward, which
   also frees the activations that the local passes still need. `mode="replace"` drops it.
5. **Build the optimizer after the decoders exist.** Decoders are created on the first
   captured activation (width read from its last dim), so `lw.parameters()` raises
   `RuntimeError` until then. Pass `example_batch=` (a `no_grad` dry run), `widths=`, or run
   one forward first.
6. **Distributed and compile.** DDP works with `locality="params"`: the local passes use
   `autograd.grad` and never trigger DDP's hooks, the final backward is the one DDP sees,
   and decoder grads are all-reduced when `torch.distributed` is initialised
   (`sync_decoders=True`). `DataParallel` and FSDP raise. With `torch.compile`, compile the
   inner layers, not the hooked root. Gradient checkpointing must be non-reentrant:
   `gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})`,
   otherwise construction raises.
7. **Memory.** NanoJev scores every candidate path in one call: `P = B x (n_layers + 1) x
   sum(candidates per question)` sequences of roughly `num_slots + question tokens` each.
   Reduce `k`, `num_slots`, or the number of selected layers (`layers="last:4"`,
   `"every:2"`); `layer_sampling=n` scores a random subset each step; `max_paths=n` (default
   64) runs NanoJev forward **and** backward in chunks of at most `n` candidate sequences
   (identical logits and gradients, peak memory of one chunk instead of the whole batch;
   unchunked, a 0.6B judge on 32 samples x 3 layers x 5 candidates keeps ~50 GB of fp32
   activations and will freeze a shared-memory laptop). `NanoJev(..., gradient_checkpointing=True)` and
   `autocast_dtype=torch.bfloat16` trade compute for memory on the judge. On Apple Silicon the
   judge caps its own MPS allocation at 75% of the recommended maximum (`mps_memory_fraction=`,
   env `JEVLOSS_MPS_MEMORY_FRACTION`) so an oversized batch raises OOM instead of swapping the
   whole machine to a halt.
8. **Padding masks.** A 2-D `attention_mask` kwarg on the root forward is captured
   automatically (1 = valid); `lw.set_mask(mask)` overrides it. `pool="mean"|"last"|"first"`
   are mask-aware and `"tokens"` compacts valid tokens to the front, so left padding is safe.
   Without a mask every position is treated as valid.
9. **One forward per step.** Captures are keyed by forward id; two forwards before
   `compute` raise ("captures come from different forwards"), and two calls of a hooked
   layer in one forward raise unless `multi_call="concat"`. Run validation forwards under
   `torch.no_grad()`, `with lw.disabled():`, or `lw.enabled = False`; hooks are no-ops there.
   `lw.remove()` (or leaving the `with lw:` block) detaches all hooks.
10. **Precision.** Decoders are fp32 and captured activations are cast to fp32; NanoJev
    runs under its own autocast (`autocast_dtype=`) on cuda/cpu. Wrapping the model forward
    in `torch.autocast` is fine. With AMP pass `scaler=` to `backward` so every pass is scaled.
11. **Small batches.** `ChoiceObjective` needs at least two distinct label values in the
    batch (or `distractors="bank"`, a FIFO of the last `bank_size` values, or a fixed
    `candidates=` list) or that sample gets no question. Boolean baselines use the batch
    majority, so a batch of two is a noisy baseline.
12. **What is saved.** `lw.state_dict()` holds only `decoders.*` plus extra state naming each
    layer, `num_slots`, `heads`, `pool` and objective text; loading rebuilds decoders from the
    tensor shapes. `save_decoders(path)` / `load_decoders(path)` are the one-liners. The
    upstream model and NanoJev are stored as plain attributes, never as submodules.
13. **Eval and grads.** Hooks do nothing when `torch.is_grad_enabled()` is False, so
    `model.eval()` plus `no_grad` costs nothing. NanoJev's own parameters never receive
    `.grad`; on HF upstreams `embed_tokens.weight.grad` stays `None` under
    `locality="params"` unless the task loss touches it.
14. **Checkpoint and attribution.** `ensure_checkpoint()` downloads `C-Tianyu/NanoJev`
    (revision `unified-games-v1`, about 2.2 GB) once to `~/.cache/jevloss/NanoJev-unified`
    and needs the `[download]` extra; pass `local_dir=` to relocate it. `jevloss` is MIT
    licensed and vendors NanoJev's `DecisionModel` (MIT, OpenJev contributors); see `NOTICE`.

## API

### `LayerwiseJEVLoss(model, jev, ...)` (alias `JEVLoss`)

| Argument | Default | Meaning |
|---|---|---|
| `model` | | Any `nn.Module`. Stored as a plain attribute, not a submodule. |
| `jev` | | A `NanoJev` (`DifferentiableNanoJev`) instance, frozen. |
| `layers` | `"all"` | `"all"`, dotted container path, `list[str]`, `list[nn.Module]`, fnmatch glob, `"last:n"`, `"every:n"`, or `predicate(name, module)`. `"all"` tries known paths (`model.layers`, `transformer.h`, `encoder.layer`, `blocks`, ...) then the container with the most parameter-bearing children; ambiguity raises. Resolved names in `lw.layer_names`. |
| `objectives` | `None` | `str` or `Objective` for every layer, a list (one per selected layer, in order), a `dict[layer_name, ...]`, or `callable(name, i, n)` (see `DepthObjectives`). Strings become `PlainObjective`. |
| `default_objective` | `None` | Used for layers missing from a dict. |
| `global_objective` | `None` | `str` or `Objective` applied to `global_source`; its gradient is not localised. |
| `global_source` | `"last_layer"` | `"last_layer"`, `"model_output"` (the `model_output=` arg of `compute`), a dotted module name, or `callable(output) -> Tensor`. |
| `locality` | `"params"` | `"params"`, `"block"`, or `False` (item 3 above). |
| `decoder` | `None` | `dict(num_slots=16, heads=8, train_scale=False)` for `StateDecoder.from_nanojev`, or `callable(upstream_dim) -> StateDecoder`. When pooling yields one token, `num_slots=None` unless set explicitly. |
| `pool` | `"tokens"` | `"tokens"`, `"mean"`, `"last"`, `"first"`, a `dict[layer, ...]`, or `callable(x, mask) -> (x, mask)`. Mask-aware. |
| `capture_fn` | `None` | `dict[layer_name, callable(output) -> Tensor]` for modules whose output is not a Tensor / tuple / `ModelOutput`. |
| `warmup_steps` | `0` | Steps during which activations are detached (decoder-only training). |
| `ramp_steps` | `0` | Steps over which the layer losses ramp linearly to full weight after warm-up. |
| `depth_weight` | `1.0` | `float`, `(first, last)` linear over depth, or `callable(i, n)`. |
| `embed_reg`, `embed_reg_weight` | `"rms"`, `1e-2` | Keeps decoded embeddings near the checkpoint's token RMS: `((rms(e) / embed_rms - 1)^2).mean()` per layer. |
| `layer_sampling` | `None` | Score a random subset of this many layers per step. |
| `max_paths` | `64` | Chunk the NanoJev forward+backward into calls of at most this many candidate sequences; bounds peak memory at one chunk's activations. `None` = one call (needs ~2.3 MB per token of activations in fp32). The returned losses still backpropagate normally. |
| `conv_grid` | `10` | `[B,C,H,W]` activations (conv nets) are average-pooled to this grid and flattened to `grid*grid` tokens before the decoder; `None` keeps every position. |
| `example_batch` | `None` | `Tensor`, `tuple` or `dict`: dry run under `no_grad` to materialise decoders now. |
| `widths` | `None` | `dict[layer_name, int]` alternative to `example_batch`. |

Other members: `compute` (also `forward`), `backward`, `materialize(...)`, `enabled`,
`disabled()`, `set_mask(mask)`, `remove()`, `save_decoders(path)`, `load_decoders(path)`,
`decoders` (`nn.ModuleDict` keyed `layer__<name with '.' -> '__'>` and `global__`), `step`.

### `compute(labels=None, annotations=None, model_output=None) -> LayerLosses`

`labels` is a sequence of str/int/float (0-d tensors are `.item()`ed; ints go through
`label_names` when given) and becomes `annotations=[{"label": l}, ...]`. Pass `annotations`
directly for richer per-sample dicts (objectives read `annotation[key]`, `key="label"` by
default). Requires exactly one hooked forward since the last `backward`; raises with a
named reason otherwise ("run the model forward with the loss enabled first", "layer X never
fired", "batch size mismatch", "activations were freed by backward; run forward again").

### `backward(losses, task_loss=None, mode="augment", retain_graph=False, scaler=None) -> float`

Performs the single NanoJev backward, the per-layer local passes, and the one final
backward for `task_loss` plus the global objective. `mode="replace"` ignores `task_loss`.
Returns `float(total + task_loss)`, clears captures, and advances `step`.

### `LayerLosses`

A `Mapping[str, Tensor]`: `losses[name]` is that layer's weighted loss and `items()`
iterates layers only. Attributes:

| Field | Meaning |
|---|---|
| `total` | What `backward` optimises: local sum normalised by the sum of active weights, plus `global_loss`, plus the embedding regulariser. |
| `local` | The normalised local sum alone. |
| `global_loss` | Loss of the global objective, or `None`. |
| `by_objective` | `dict[objective_name, Tensor]` mean loss per objective. |
| `counts` | `dict[layer, int]` number of scored questions per layer. |
| `info_gain` | `dict[layer, float]`: `baseline_nll - nll`, how much better than chance the layer is read. |
| `state_rms` | `dict[layer, float]` RMS of the decoded state embeddings. |
| `outputs` | `dict[layer, NanoJevOutput]` (detached logits, `valid`, `state_index`, `questions`). |
| `step` | The step counter at compute time. |

### Objectives (`jevloss.objectives`)

| Class | Key arguments | Target and baseline |
|---|---|---|
| `PlainObjective(text, mode="choice")` | `mode` in `"choice"`, `"boolean"`, `"score"`; forwards `k`, `levels`, `criteria`, `seed`. The user-facing wrapper; a bare string becomes one. | Delegates to the class below. |
| `ChoiceObjective(instructions, k=4, candidates=None, distractors="batch")` | Truth plus up to `k-1` distinct values from the batch, `candidates` list, or a FIFO bank (`"bank"`, `bank_size=2048`); `format_fn`, `seed`. | Index of the truth slot, shuffled per step; `baseline_nll = log k_i`. Fewer than two distinct values: no question. |
| `BooleanObjective(instructions, criteria=None, balance=False)` | Optional true/false criteria; `balance` reweights by inverse class frequency. | `bool(annotation[key])`; baseline `-log p_majority`. |
| `PairedBooleanObjective(template, p_swap=0.5)` | `template` contains `{value}`; with probability `p_swap` another sample's value is substituted. | True if the value is the sample's own. |
| `ScoreObjective(instructions, levels, smoothing=0.0)` | Ordered level names; `smoothing` spreads a triangular target over neighbours. | Level index. |
| `CustomObjective(questions, target_fn)` (alias `QuestionSet`) | Raw NanoJev question dicts keyed by `qid`; `target_fn(annotation) -> dict[qid, Target]`. Missing qid skips that question. | Whatever `target_fn` returns (index or distribution). |
| `DepthObjectives({(lo, hi): objective_or_str})` | Callable `(name, i, n) -> Objective` selecting the bin containing `i / (n - 1)`; last bin inclusive. | |

Every objective has `name`, `weight`, `key`, `build(jev, annotations, i)`,
`compile(jev, annotations)` and `sanity_check(jev, annotations, render_fn)`, which scores
ground-truth text through `forward_text` and returns `{"nll", "accuracy", "baseline_nll"}`.

### Lower level

`NanoJev.from_checkpoint(dir, device=None, autocast_dtype=None, gradient_checkpointing=False, mps_memory_fraction=0.75)`,
`forward_text(states, questions)`, `forward_embeds(embeds, lengths, questions)`,
`forward_soft_tokens(probs, lengths, questions)`, `nll(out, target)`, `compile_question(dict, qid)`;
`StateDecoder(upstream_dim, jev_dim, num_slots=None, heads=8, embed_rms=1.0)` and
`StateDecoder.from_nanojev(jev, upstream_dim, num_slots, heads)`. These are what
`LayerwiseJEVLoss` is built from and can be used on their own (see `jevloss/core.py`).

## How it works

NanoJev answers a question about a piece of text by scoring each candidate answer as its
own path: `State: <text>` followed by the question and one candidate, with a decision head
on the final token. `jevloss` keeps the question and candidate tokens (compiled once and
cached by text) and replaces the state text with embeddings.

Each selected layer gets a forward hook that records its activation. At `compute`, every
activation is pooled, cast to fp32, and fed through that layer's `StateDecoder`, a small
Perceiver-style resampler whose learned queries cross-attend to the activation and emit
`num_slots` vectors in NanoJev's input-embedding space, LayerNorm'd and rescaled to the
checkpoint's token RMS. The objectives turn the batch's labels into one question per row
(for `Choice`: the truth plus distractors drawn from the other labels, shuffled every step).
All layers' decoded states are concatenated on the batch axis and go through **one**
`forward_embeds` call, so the cost of the judge does not grow with the number of layers
beyond the batch it sees.

Locality comes from a detach cut. The concatenated states `E_all` are detached into `E`,
which is what NanoJev consumes. `backward` first takes `autograd.grad(total, E)`: the single
NanoJev backward, giving a gradient per row. It then runs `autograd.grad` from each layer's
rows of `E_all` into that layer's parameters and its decoder only, accumulating into `.grad`
by hand. Finally, the global rows and `task_loss` are combined into the one ordinary
`backward()` that flows through the whole network. No gradient gates, no hooks on tensors:
a layer's sentence cannot influence any layer below it.

## License

MIT (see `LICENSE`). NanoJev code and checkpoint are by the OpenJev contributors under MIT;
see `NOTICE`.
