This repository provides the official implementation of DyME (Dynamically selecting between Memorization and Exploration), accepted at ICLR 2026.
Overview
Small-scale Vision-Language Models (SVLMs) are highly suited for proprietary tasks, but equipping them with reasoning and thinking capabilities remains challenging. Traditional Supervised Fine-Tuning (SFT) can force memorization of pseudo thinking traces, while Reinforcement Learning with Verifiable Reward (RLVR) often leads to unstable exploration (advantage collapse) due to limited model capacity.
DyME is a novel training paradigm that dynamically synergizes SFT and RLVR. At each optimization step, DyME dynamically selects between Memorization (via SFT) and Exploration (via RLVR), ensuring every update contributes to an optimal trade-off. To further enhance this, we introduce a Visual Supervision mechanism (a visual checker and refiner) to inject dynamically enhanced, image-grounded guidance during training.
Extensive experiments show that DyME delivers substantial performance improvements, establishing it as a robust strategy for stabilizing SVLM learning.
Repository Structure
text
1DyME/
2├── client_utils/ # Client tools for online Visual Supervision (LLM API)
3├── data/ # Preprocessed textual datasets
4├── data_utils/ # Data processing and formatting scripts
5│ ├── aokvqa/
6│ ├── chart/
7│ └── commom_util.py
8├── eval/ # Evaluation scripts for different benchmarks
9├── reward_utils/ # Reward function implementations for RLVR
10├── config/ # Modular configuration files for experiments
11├── opsd_utils/ # Privileged-context OPSD / TriMode extensions for DyMETrainer
12├── default_config.yaml # Default DDP (MULTI_GPU, no DeepSpeed required)
13├── default_config_deepspeed.yaml # Optional ZeRO-0 only (no sharding); needs pip install deepspeed
14├── default_config_zero2.yaml # ZeRO-2 student sharding (OPD 7B colocate)
15├── default_config_zero3_colocate.yaml # ZeRO-3 + CPU optimizer offload (tight VRAM)
16├── configs/deepspeed/ # DeepSpeed JSON templates (HF official "auto" fields)
17├── main.py # Entry point for DyME training
18├── main_*.py # Additional experimental variants (e.g., 7B, LLM-only)
19├── requirements.txt # Python dependencies
20└── ...
Configuration
Before launching training, please prepare the relevant configuration files. The main settings are managed through configuration files such as config/config.yaml and default_config.yaml.
This configuration is required when Visual Supervision is enabled. It specifies the online large-model API used by the visual checker and visual refiner.
training
This section contains standard training hyperparameters for both the memorization phase and the exploration phase, including optimizer settings, batch size, learning rate, and related options.
rl
This section defines critical variables for reward computation and response parsing during RLVR training. In particular, the following delimiters must be properly specified:
answer_flag: used to explicitly separate the final answer from auxiliary generated content such as intermediate reasoning traces.
end_flag: used to mark the end of generation.
These delimiters are essential for stable parsing, reward assignment, and evaluation consistency.
opsd (OPSD / TriMode)
config/config.yaml explicitly defines opsd. When enabled=false (default), training follows original DyME behavior. Enable it in the selected YAML (or use a documented CLI switch) to activate privileged-context Self-OPSD inside DyMETrainer.
Field
Description
enabled
Master switch. False → original DyME only.
mode
Routing mode (see table below).
privileged_profile
Teacher preset: text | visual | hybrid (explicitly set in every YAML).
privileged_providers
Override provider list; default derived from profile.
privileged_image
Teacher image layout: modesingle (ChartQA default) or dual (full + crop); plus crop_strategy, bbox_coord, margin_ratio.
Recoverability gate: privileged_available (default) or logprob_gain.
loss.beta
JSD temperature for OPSD distillation.
loss.opsd_weight / grpo_weight / sft_weight
Per-mode loss weights.
Routing modes (mode):
Mode
Behavior
dyme
Original DyME: any correct rollout → GRPO; all wrong → SFT.
trimode
Any correct → OPSD (replaces GRPO); all wrong → SFT (DyME cold-start via sft_check, ignores recoverable).
opd_only
Isolated post-SFT OPD stage: all rollout completions use OPD; no reward routing, GRPO, online SFT, or teacher-SFT repair. Teacher probe, structured trajectory FKL, visual checker, and refiner may be enabled as diagnostics/auxiliary distillation, but cannot select, replace, or discard an OPD row.
replace_sft
Any correct → GRPO; all wrong → OPSD (no SFT).
opsd_on_wrong
Any correct → GRPO; all wrong + recoverable → OPSD; all wrong + not recoverable → SFT (legacy three-way routing).
grpo_opsd_joint
Any correct → GRPO (+ optional joint OPSD loss); all wrong + recoverable → OPSD; else SFT.
Under trimode, the SFT share is determined by accuracy (how often prompts are all-wrong) and DyME's per-group sft_check (teacher injection on the first generation only)—no extra sft_ratio hyperparameter.
Privileged profiles (privileged_profile):
Profile
Teacher images
Teacher text suffix
text
Single full image (same as student)
hint + answer
visual
Dual: full + evidence crop
Visual Facts only (no answer leak)
hybrid
Single full image by default (privileged_image.mode=single); dual with mode=dual
Visual Facts + hint + answer
Student collate_fn never reads privileged fields. With privileged_image.mode=dual, teacher forward uses [full, crop]; crop comes from normalized evidence_bbox (C2), A-OKVQA visual_fact heuristic (D2), or center fallback (D1). ChartQA defaults to single (no crop zoom).
text — uses the hint / answer fields in training samples.
visual_facts — uses visual_fact JSON (B1 raw string), plus ChartQA visual_fact_hint (F1) and visual_fact_deplot (F2).
crop — evidence region as second teacher image (via image_utils, not a text suffix).
hybrid — combines text + visual_facts providers per profile.
Debug / artifact logging
Verbose OPSD logs: set opsd.debug.verbose: true in the YAML or pass
--opsd_debug.
Full diagnostic bundle every N steps: set opsd.debug.detail_every in the
YAML or pass --opsd_detail_every N.
On detail steps, teacher privileged images are saved under {output_dir}/logs/images/ as step_XXXXXX_idx_Y_full.png, _crop.png, and _meta.json (controlled by privileged_debug.max_samples_per_detail).
ChartQA visual-facts preprocessing (run on server before TriMode training)
TriMode with privileged_providers=text,visual_facts requires visual_fact_hint / visual_fact_deplot (and optionally visual_fact) on each sample. Raw train_medium.json only has hint — without this step, logs show visual_fact_len=0 and the VisualFacts teacher channel is empty.
config/config.yaml points train_dataset at data/chartqa/train_medium_vf_full.json. Generated *_vf_*.json files are gitignored — generate them on each server (or copy from shared storage); do not rely on cloning them from GitHub.
scripts/train_local_gpus.sh will auto-run the two Python steps above if train_medium_vf_full.json is missing.
Training examples (TriMode + hybrid default)
bash
1# Text-only OPSD ablation2python main.py --config trimode --opsd_privilege_profile text
34# Vision-OPD style (no answer text to teacher)5python main.py --config trimode --opsd_privilege_profile visual
67# Full hybrid (default in config_trimode)8python main.py --config trimode --opsd_privilege_profile hybrid --opsd_detail_every 10
The strict OPD image-checker recipe validates its configured precomputed
dataset before launching Accelerate. Its YAML already contains the complete
DePlot path and expected-sample contract; no launch-time recipe overrides are
required:
The launcher exits before model initialization when the configured file is
missing, has placeholder/invalid DePlot rows, missing or unreadable images, or
lacks successful Qwen rewrite provenance. It prefers
data/chartqa/train_new_prerefine_vf_full_real.json and accepts the historical
train_new_prerefine_vf_full.json name only when that file itself passes the
same checks.
Privileged sample schema
Field
Used by
Notes
prompt, image
Student + teacher
Student always single full image
hint, answer
Teacher (text / hybrid)
Never in student collate
visual_fact
Teacher
Raw JSON string (A-OKVQA)
visual_fact_hint
Teacher (ChartQA F1)
Hint placeholder pipeline
visual_fact_deplot
Teacher (ChartQA F2)
DePlot parsed_table text (google/deplot; placeholder skipped)
evidence_bbox
Teacher crop
Normalized [x0,y0,x1,y1] in [0,1]
Adapter helpers for future datasets: data_utils/privileged_schema.py (normalize_evidence_bbox, parse_visual_fact, resolve_crop_bbox).
For legacy ChartQA single-field preprocessing, see scripts/build_visual_facts_chartqa.py.
Data Preparation
We provide example preprocessing scripts in the data_utils/ directory. After preprocessing, the training data should be organized as a list of dictionaries (e.g., metadata_list) following the format below:
python
1metadata_list.append({2"question": question,# Full prompt used for training3"question_wo_prompt": question,# Raw question without prompt template4"answer": answer,# SFT target; should follow the answer_flag format5"image": image_save_path,# Local path to the corresponding image6})
Field Description
question: the complete model input used during training.
question_wo_prompt: the raw question content without any additional prompt wrapper.
answer: the training target for SFT; this field should be formatted consistently with the delimiter specification in RL_CONFIG.
image: the local file path of the associated image, if applicable.
Environment Setup
Please first install the required dependencies and configure the distributed training environment:
Preprocessed text annotations with hints live separately under data/chartqa/ and data/aokvqa/. Image paths inside those JSON files are resolved automatically at load time (legacy prefixes like /chartqa_output/ map to data/images/chartqa/).
Demo Samples
A small subset of demo images for verifying the data loading pipeline may be provided in a future update.
Dataset Examples
ChartQA
ChartQA is a visual question answering benchmark grounded in chart images. To illustrate different supervision granularities, we provide representative examples with three levels of reasoning-trace quality: High, Medium, and Low.
Example
ChartQA Example
High-quality Example
High-quality ChartQA Example
json
1{2"question":"When does the unfavorable view reach the peak?",3"answer":"2017",4"hint":"<SUMMARY> To solve the problem, I will examine the image to identify trends in unfavorable views of Pakistan in India over time. I'll closely inspect the data points within the graph to determine the year where the \"very unfavorable view\" reaches its peak. This involves identifying the maximum value on the vertical axis and noting the corresponding year on the horizontal axis. </SUMMARY> \n\n<CAPTION> The image is a line graph titled \"Very unfavorable views of Pakistan increasing in India,\" with the subtitle \"Very unfavorable view of Pakistan.\" The y-axis represents the percentage of unfavorable views, ranging from 0% to 100%. The x-axis displays years from 2013 to 2017. The data points show the percentages of very unfavorable views over these years, with specific values marked: 54% in 2013, 49% in 2014, 51% in 2015, 55% in 2016, and 64% in 2017. The graph shows a general upward trend in unfavorable views, peaking in 2017. </CAPTION> \n\n<REASONING> To determine when the unfavorable view reaches its peak, one should observe the graph for the data point with the highest percentage on the y-axis. The graph shows percentages for each year from 2013 to 2017: starting at 54% in 2013, decreasing to 49% in 2014, and then gradually increasing to 51% in 2015 and 55% in 2016. The graph culminates with the highest percentage of 64% in 2017. Thus, the peak of unfavorable views is associated with the year 2017. </REASONING> \n\n<CONCLUSION> 2017 </CONCLUSION>"5}
Medium-quality Example
Medium-quality ChartQA Example
json
1{2"question":"When does the unfavorable view reach the peak?",3"answer":"2017",4"hint":"Goal: Find the year when the unfavorable view reaches its peak.\nObservation: The data shows the values for each year are: 2013: 0, 2014: 0, 2015: 0, 2016: 55, and 2017: 64.\nReasoning: By comparing the values in each year, the highest value is 64, which occurs in 2017.\nConclusion: The unfavorable view reaches its peak in 2017."5}
Low-quality Example
Low-quality ChartQA Example
json
1{2"question":"When does the unfavorable view reach the peak?",3"answer":"2017",4"hint":"I'm trying to figure out the year when the unfavorable view reaches its highest point. Looking at the data, I see that the values for each year are pretty low until 2016, where it jumps to 55. But the peak doesn't happen until 2017, when the value spikes to 64. So, it seems like the unfavorable view really hits its maximum in 2017."5}
A-OKVQA
A-OKVQA is an open-ended visual question answering benchmark that requires world knowledge, commonsense reasoning, and visual understanding. Below we provide a representative example together with its corresponding annotation.
Example
A-OKVQA Example
View A-OKVQA JSON Example
json
1{2"question":"What is the man by the bags awaiting?",3"answer":"cab",4"visual_fact":"{\n \"description\": \"The image shows a man standing in the middle of a street, facing away from the camera. He is holding a red bag in one hand and appears to be pulling a black suitcase with wheels. Another black suitcase is lying on the ground near him. The setting is an urban area with houses, parked cars, and trees in the background. The man seems to be waiting or preparing to cross the street.\",\n \"objects\": [\n {\n \"name\": \"man\",\n \"attributes\": [\"wearing a light blue and white shirt\", \"blue jeans\", \"carrying a red bag\", \"pulling a black suitcase\"],\n \"position\": \"center\"\n },\n {\n \"name\": \"red bag\",\n \"attributes\": [\"held by the man\"],\n \"position\": \"left side of the man\"\n },\n {\n \"name\": \"black suitcase\",\n \"attributes\": [\"with wheels\", \"being pulled by the man\"],\n \"position\": \"near the man's feet\"\n },\n {\n \"name\": \"black suitcase\",\n \"attributes\": [\"on the ground\"],\n \"position\": \"on the ground near the man\"\n },\n {\n \"name\": \"street\",\n \"attributes\": [\"asphalt\", \"urban setting\"],\n \"position\": \"foreground\"\n },\n {\n \"name\": \"houses\",\n \"attributes\": [\"visible in the background\"],\n \"position\": \"left side\"\n },\n {\n \"name\": \"parked cars\",\n \"attributes\": [\"red SUV\", \"other vehicles\"],\n \"position\": \"left and center background\"\n },\n {\n \"name\": \"trees\",\n \"attributes\": [\"green foliage\"],\n \"position\": \"right side\"\n }\n ]\n}",5"hint":"A train would not be on the street, he would not have luggage waiting for a delivery, and the skateboarder is there and not paying attention to him, so a cab is the only plausible answer."6}
GSM8K
GSM8K is a mathematical word problem benchmark. Since it is text-only, we provide a representative question-answer example together with its reasoning trace.
View GSM8K JSON Example
json
1{2"question":"Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?",3"answer":"72",4"hint":"Natalia sold 48/2 = <<48/2=24>>24 clips in May.\nNatalia sold 48+24 = <<48+24=72>>72 clips altogether in April and May.\n#### 72"5}
Training
All training scripts are launched using accelerate. Pass --config as a complete
YAML configuration path (recommended) or a shorthand alias (norm, trimode,
llavacot, low, aok). Python configuration files are rejected.
Important:num_processes must match the number of visible GPUs on your node. Helper scripts auto-detect GPU count and use native PyTorch DDP (default_config.yaml, distributed_type: MULTI_GPU) — DeepSpeed is not required for 0.5B multi-GPU training.
Optional: if you already have deepspeed installed and want the Accelerate integration without parameter sharding, use ZeRO-0 (default_config_deepspeed.yaml, zero_stage: 0). Do not use ZeRO-2/3 for 0.5B-only RLSD unless you need the integration path.
7B OPD (student + frozen teacher on each GPU): default ZeRO-0 (no student sharding) when VRAM is sufficient — fastest on 8× H800. The frozen 7B teacher stays outside DeepSpeed on cuda:{LOCAL_RANK}.
Or override explicitly: NUM_GPUS=4 bash scripts/train_trimode.sh
For TriMode on all visible local GPUs (auto-detect via CUDA_VISIBLE_DEVICES / torch.cuda.device_count()):
bash
1# 1) One-time (or when raw data changes): enrich ChartQA JSON on the server — see2# "ChartQA visual-facts preprocessing" above. train_local_gpus.sh also auto-runs3# this if train_medium_vf_full.json is absent.45# 2) Start training (all recipe values are in YAML)6bash scripts/train_local_gpus.sh
78# To use the pre-antidegeneration recipe, invoke it explicitly:9# accelerate launch --config_file default_config.yaml --num_processes 4 main.py \10# --config config/config_trimode.yaml --mode rl
scripts/train_local_gpus.sh defaults to config/config_trimode_antidegen.yaml (alias trimode_antidegen). Overrides are based on offline analysis of train_trimode_4gpu_20260610_173637.log (1225 steps):
Success criteria (candidate vs baseline): step 1 clip < 1.0; LOGIT_MODE_COLLAPSE count down >30%; opsd_mask mean > 8%; step 200+ mean_length median < 130. RL_ZERO_SIGNAL may remain high (trimode design).
Logs are prefixed with [OPSD-DEBUG] and include rank, step, [SYNC_POINT] markers before every distributed collective in the OPSD chain (reward gather, teacher prompt build, metrics gather, OPSD loss). Search the log for the last [SYNC_POINT] on each rank to locate where a hang occurred.
You can also use the helper script (debug + tee enabled by default):
bash scripts/train_trimode.sh
Set opsd.debug.verbose: false in the selected YAML when detailed debug logging is not needed.
Periodic weak-signal diagnostics ([OPSD-DETAIL])
Separate from per-step [OPSD-DEBUG] spam: every N global steps (default 10, rank 0 only) a full diagnostic bundle is printed to investigate reward ≈ 0 and gradient ≈ 0 while the OPSD chain still runs:
Generation: EOS rate, clipped ratio, effective completion tokens, decoded samples
Per-generate probe ([OPSD-PROBE]) — enabled by default in config/config_trimode.yaml; fires on every (re)generate on rank 0 (no need to wait for step 10). Logs raw completion_ids, decode with/without special tokens, eos_idx, flags ONE_TOKEN / EMPTY_DECODE / FIRST_IS_EOS, and patterns PAREN_THEN_EOS / REPEAT_LOOP. Disable in YAML or with --no_opsd_probe_on_generate.
Deep generate debug ([OPSD-GENDBG]) — runs alongside [OPSD-PROBE] when probe is enabled. Before each model.generate, logs model training context, prompt tail tokens/decode, and first-token logits (p_eos, p_token_340, entropy, top5) via per-sample forward (up to probe_sample_count, default 4) to avoid OOM on large VLM batches. After generate, logs greedy-vs-actual first token, delta vs previous regenerate, and cross-rank summary.
Large one_token_count gap across ranks in cross_rank
Data sharding / batch composition
delta_one_token_count spikes at generate_call_index>=2
Weight drift after optimizer step
For a persistent probe change, copy the selected YAML and edit
opsd.debug.probe_first_token_logits, probe_prompt_tail_tokens, or
probe_log_model_context explicitly.
2. Training TriMode (DyME + OPSD)
Use config/config_trimode.yaml (OPSD pre-enabled) or override on the base config via CLI:
2b. RLSD / anti-leakage OPSD (recommended for ChartQA)
trimode routes OPSD on correct completions and injects gold answer into the teacher prompt (information leakage). Use rlsd instead:
Correct → GRPO (on-policy self-learning, no privileged suffix)
Wrong → same-prompt OPSD / OPD (no [Reference Answer] in teacher)
All-wrong group → online SFT replace on the first generation (DyME cold-start; no separate offline SFT phase)
Important — online SFT ≠ offline SFT: From step 0, training is always RL + sparse online SFT (typically 1/8 of completions per prompt when the group is all-wrong). There is no dedicated SFT-only phase unless you run a separate offline stage (see below).
GT injection slots per all-wrong group during warmup
OPD recipe check:config/config_opd_7b_chartqa.yaml is fully expanded. If logs show max_new_tokens=150, temperature=0.7, you selected the anti-degeneration recipe instead of the intended OPD YAML.
Stop-training heuristics: If after ~200 steps you see degenerate_rate≈1, opsd_mask_true=0, grad_norm=0, and format_mean≈1 with accuracy=0, the run is collapsed — restart from base 0.5B or an early checkpoint.
Run offline SFT, then copy config/config_opd_only_7b_chartqa.yaml, set
model.pretrained_model_path to the SFT final_checkpoint, select a fresh
training.dyme_args.output_dir, and launch that YAML. The OPD-only recipe
does not read a student or teacher path from the environment.
Pure OPD-only smoke: after setting the two explicit local model paths in
the selected YAML, run one isolated OPD step (no routing):
teacher_probe, teacher_trajectory, and visual checker/refiner may remain
enabled in this stage. Their raw outputs are saved under the run directory,
but their results cannot convert a row to SFT/GRPO or remove it from OPD.
1# Default: teacher on each rank's GPU (cuda:LOCAL_RANK). 2-GPU: student+teacher share the same card per rank.2# Choose `model.teacher_device_map` directly in the selected YAML.3# Vocab-alignment diagnostics are controlled by `opsd.debug` in the YAML.4bash scripts/train_opd_7b_chartqa.sh
Note: main.py --mode rl --config config/config.yaml uses dyme_args (not the unused grpo_args block in the same file). Pure GRPO baselines use main_rebuttal.py.
Helper scripts (under scripts/):
bash
1# TriMode on ChartQA (legacy; leakage risk on ChartQA)2bash scripts/train_trimode.sh
34# Anti-leakage RLSD (recommended)5bash scripts/train_rlsd_chartqa.sh
67# Choose an ablation by copying a complete YAML and explicitly setting8# its `opsd` fields. `scripts/train_baselines.sh` is retired because it used9# environment variables to mutate recipes.1011# Post-training eval (set CHECKPOINT_DIR)12CHECKPOINT_DIR=./outputs/trimode-chartqa/final_checkpoint bash scripts/run_eval_ablation.sh
3. Reproducing Baselines
To reproduce baseline settings such as standard SFT or RL training, use main_sft.py (offline ChartQA SFT) or main.py with --opsd_enabled off for pure DyME.
(main_rebuttal.py is referenced in the original DyME paper repo but is not shipped here; use main_sft.py + main.py instead.)
4. Additional Experimental Variants
For specific experimental settings such as different model scales or architecture-specific ablations, please use the corresponding scripts:
main_7B.py: experiments at the 7B scale
main_llm.py: LLM-specific variants
main_change.py: additional ablation settings
5. Historical campaign runners
bash
1The prior PCD/DePlot campaign shells used `DYME_*` environment-variable
2overrides and are retained only as historical records. They are not valid
3training entry points under the YAML-only system. Create a complete YAML for4each experiment and invoke `main.py --config <recipe.yaml>` instead.
6. PCD-OPD Paper Artifacts
Fill docs/figures/pcd_paper/run_manifest.csv with the four no-VS runs, then build the non-main-result paper artifacts:
Before running evaluation, please open the corresponding evaluation script (for example, eval_chartqa.py) and modify the following fields as needed:
model_id: the path or identifier of the checkpoint to be evaluated
prompt templates: these should match the formatting used during training
Ensuring consistency between training and evaluation prompts is important for obtaining reliable results.
Citation
If you find this repository useful in your research, please consider citing our paper:
bibtex
1@inproceedings{dyme2026,
2 title={Empowering Small VLMs to Think with Dynamic Memorization and Exploration},
3 author={Jiazhen Liu, Yuchuan Deng, Long Chen},
4 booktitle={ICLR},
5 year={2026},
6}
ChartQA SFT student checkpoint
The SFT-only LLaVA-OneVision-Qwen2 0.5B student trained for one epoch on the
4,576-example DyME ChartQA protocol is available under
models/chartqa-dyme-sft-qwen4576-official05b-1ep/. This checkpoint predates
the subsequent OPD runs and includes the processor/tokenizer files required
for standalone loading. See the checkpoint-local README for provenance,
loading instructions, and its SHA-256 checksum.