Skip to content

Add vision_only observer mode for text/vision expert-usage skew analysis - #31

Open
aquilarubra wants to merge 5 commits into
CerebrasResearch:mainfrom
aquilarubra:pr/vision-usage-report
Open

Add vision_only observer mode for text/vision expert-usage skew analysis#31
aquilarubra wants to merge 5 commits into
CerebrasResearch:mainfrom
aquilarubra:pr/vision-usage-report

Conversation

@aquilarubra

Copy link
Copy Markdown

Depends on #30 — stacked on top of it (uses the vision_dataset/vision_samples
fields it adds).

What

Adds a --vision_only flag to LayerwiseArgs (args.py) that, when set,
skips text calibration batches entirely — the observer state reflects only
the --vision_dataset samples (requires it to be set).

Why

Layerwise pruning's expert saliency is measured on whatever calibration data
you feed it. If you calibrate text-only (the default/upstream behavior),
experts that predominantly serve vision tokens look unsalient and get pruned
first — sometimes desirable (a text-only serving target), sometimes not
(you want to keep some multimodal capability).

Deciding how aggressively you can lean on that effect currently requires
guessing a --compression_ratio/keep_ratio and hoping. With --vision_only,
you can run the observer twice — once text-only, once vision-only — and diff
per-expert usage share between the two runs to see, empirically, which
experts are vision-skewed for this checkpoint's actual routing statistics,
before picking a pruning ratio. (We use this internally to build a
prune-ratio recommendation report; happy to share that tooling too if useful
upstream, but it's built around our own disk-streaming driver scripts so
didn't include it here to keep this PR minimal.)

Test plan

  • --vision_only without --vision_dataset raises a clear error
  • With both set, data_batches reflects only the vision samples (text
    batch preparation is skipped)
  • Without --vision_only (default False), behavior is unchanged from
    the current vision_dataset-only opt-in

Registers Qwen3_5MoeForConditionalGeneration in MODEL_ATTRS and
generalizes get_moe() to walk model.model.language_model.layers, not
just model.model.layers, for this architecture's nested multimodal
wrapper. Adds a matching observer hook config (num_experts/top_k live
on .experts/.gate submodules rather than the MoE block itself here).

Generalizes the fused-expert pruning branch, which was hardcoded to
Llama4's moe.router attribute and nn.Linear-style router with
out_features, to also support Qwen3.5's .gate raw weight Parameter.
Extracts select_retained_experts() as a standalone function from
prune()'s inline body so the same selection logic can be reused
outside an in-memory model (disk-based surgery).

Signed-off-by: Fabrizio del Tin <devotedmystic@gmail.com>
REAP's layerwise-observer path was RAM-bounded only in appearance: the
observer phase loaded the entire model onto CPU via device_map="cpu"
before any block-wise logic ran, so peak RSS still scaled with total
checkpoint size rather than one layer's size. This makes it possible
to prune a checkpoint far larger than available RAM+VRAM.

- New src/reap/disk_stream_util.py: reads/writes checkpoint tensors
  directly from safetensors shards, opening and closing each shard
  scoped to a single read (deliberately never caches file handles,
  since a held mmap handle keeps its touched pages resident in RSS).
- layerwise_prune.py: replaces the full-RAM device_map="cpu" load with
  accelerate.init_empty_weights() (meta tensors) plus real
  materialization of only the embedding table, for local checkpoint
  directories (Hub model ids keep the original load path).
- layerwise_observer.py: generalizes the fused_experts branch's router
  lookup (was hardcoded to moe.router) and adds a dense
  all-experts-all-tokens fallback for architectures whose experts need
  top-k routing args to call (Qwen3.5, unlike Llama4's simpler dense
  callable convention). Adds dual-mask support (ReplayBatch.causal_mask)
  so hybrid linear/full-attention models get the correct mask per layer
  type instead of replaying whichever mask block 0 received. Extends
  _move_block()/_offload_current_block() to materialize/free a block's
  real tensors from disk on demand via the new streaming primitive,
  instead of only supporting already-CPU-resident blocks.

Signed-off-by: Fabrizio del Tin <devotedmystic@gmail.com>
transformers >=5.10 dispatches the fused-experts forward to
torch._grouped_mm when available, whose meta registration hard-requires
BF16 inputs. This layerwise replay runs in float32 (RoPE cos/sin
promote hidden states through the chain), so force the eager
per-expert loop instead, which is dtype-agnostic. Observer throughput
is dominated by disk streaming, not the expert matmul dispatch, so
this has no meaningful performance cost.

Signed-off-by: Fabrizio del Tin <devotedmystic@gmail.com>
REAP's expert saliency is normally measured on text-only calibration,
so experts that predominantly serve image tokens look unsalient and
get pruned first even on VLM checkpoints. Adds an optional
--vision_dataset (plus --vision_samples/--vision_split) LayerwiseArgs
flag: when set, image+text calibration batches (from a local image
directory or an HF dataset with an 'image' column) are appended to the
text batches, and the vision tower is materialized from the disk-
stream index so they can run. Off by default (text-only, matching
existing behavior).

New src/reap/vision_calib.py builds one processor batch dict per
image sample; LayerwiseMoEObserver's existing input-forwarding already
passes arbitrary tensor-valued dict entries into model(**batch), so no
changes were needed to the observer/replay path itself.

Signed-off-by: Fabrizio del Tin <devotedmystic@gmail.com>
Skips text calibration batches entirely when set (requires vision_dataset),
so the observer state reflects only vision-token routing. Lets a new driver
script diff a vision-only observer pass against a normal text-only pass to
find which experts are vision-skewed, and at what keep_ratio REAP's pruning
starts cutting into text-load-bearing experts instead of just vision ones.

Signed-off-by: Fabrizio del Tin <devotedmystic@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant