DETAILED GUIDE: How VLM_finetune/FT.py Works (LoRA multi-GPU fine-tuning)
=====================================================================

Audience
--------
This document is written for someone who wants to understand the fine-tuning pipeline end-to-end,
even if they do NOT know what LoRA is, how multi-GPU training works, or how Hugging Face training
scripts are typically structured.

It explains:
- What happens when you run VLM_finetune/FT.py
- What each command-line flag changes
- Which external files FT.py relies on, and what they do
- How the dataset JSON is expected to look
- What is being trained (LoRA adapters) vs what is frozen
- How outputs are produced (adapters, checkpoints, optional merged model)


0) Quick map of the relevant files
---------------------------------
Main launcher:
- /users/<USER>/VLM_finetune/FT.py

Fine-tuning “worker” script that does the real training:
- /users/<USER>/VLM_finetune/finetune/finetune.py

Dataset + image/text preprocessing used by finetune.py:
- /users/<USER>/VLM_finetune/finetune/data_mix.py
- /users/<USER>/VLM_finetune/finetune/ixc_utils.py

DeepSpeed configs (optional):
- /users/<USER>/VLM_finetune/finetune/ds_config_zero2.json
- /users/<USER>/VLM_finetune/finetune/ds_config_zero3.json

Example environment setup helper (optional):
- /users/<USER>/VLM_finetune/script_conda.sh

A short “how to run” note that matches FT.py behavior:
- /users/<USER>/VLM_finetune/finetune/FINETUNE_GUIDE.txt

Datasets used by default:
- /users/<USER>/vlm_conversations_train.json
- /users/<USER>/vlm_conversations_val.json

External (installed) Python packages FT.py expects:
- torch, torchvision
- transformers
- accelerate
- peft
- PIL (Pillow)
- einops, timm, sentencepiece (used by the underlying model/vision stack)

External (downloaded at runtime, typically via Hugging Face Hub):
- Base model weights and code, default: internlm/internlm-xcomposer2-4khd-7b
  (loaded with trust_remote_code=True)


1) What problem FT.py solves
----------------------------
The base model (InternLM-XComposer2) is large and expensive to fine-tune.
FT.py exists to make a “server-friendly” fine-tuning run easy and reproducible:

- It validates dataset paths.
- It checks for required Python dependencies.
- It detects available GPUs and uses all of them by default.
- It launches distributed training with torchrun (torch.distributed.run).
- It always trains with LoRA adapters (parameter-efficient fine-tuning).
- It can optionally merge the LoRA adapters back into the base model at the end.

Important: FT.py is NOT the training algorithm itself.
FT.py is a launcher. The actual model loading, dataset building, and training loop are in:
  /users/<USER>/VLM_finetune/finetune/finetune.py


2) LoRA explained from scratch (no prior knowledge assumed)
----------------------------------------------------------
2.1 Full fine-tuning vs LoRA
- Full fine-tuning: you update (almost) all model weights.
  - Pros: maximum flexibility.
  - Cons: extremely heavy in GPU memory and compute; checkpoints are huge.

- LoRA fine-tuning (“Low-Rank Adaptation”): you keep the original weights frozen and train
  small additional matrices (“adapters”) that sit inside certain linear layers.
  - Pros: dramatically fewer trainable parameters, often much less GPU memory.
  - Cons: you must keep the base model + adapters together at inference time (unless you merge).

2.2 The intuition
Many transformer layers contain linear projections (matrix multiplications) like:
  y = W x
where W is a large matrix.

LoRA modifies this to:
  y = (W + ΔW) x
but instead of training the full ΔW (same shape as W), LoRA represents it as:
  ΔW = (α / r) * B A
where:
- A has shape (r, in_features)
- B has shape (out_features, r)
- r is “rank” (small, like 8/16/64)
- α is a scaling factor

So you only train A and B (small) while W remains frozen.

2.3 What gets saved
When LoRA is used, the output directory usually contains:
- adapter_config.json
- adapter_model.safetensors  (or adapter_model.bin depending on setup)
- tokenizer files (tokenizer.model, tokenizer_config.json, etc.)
- trainer_state.json, checkpoint-* folders (depending on save strategy)

The adapters are NOT a full model by themselves. They must be loaded on top of the base model.
FT.py also provides an optional “merge” step to create a standalone merged model.


3) Step-by-step: what happens when you run FT.py
------------------------------------------------
The overall flow is:

  You run:
    python /users/<USER>/VLM_finetune/FT.py [args]

  FT.py does:
    (A) Validate environment + dataset
    (B) Locate helper training code in /users/<USER>/VLM_finetune/finetune/
    (C) Build a command line that calls finetune/finetune.py with the right flags
    (D) Launch it with torchrun across all GPUs (or single-process)
    (E) Optionally merge adapters into a full model

Below is the detailed walk-through.


3.A Environment and dependency checks (FT.py)
--------------------------------------------
Function: _assert_deps()
- FT.py tries importing: torch, transformers, accelerate, peft, torchvision, PIL
- If anything is missing, FT.py raises a RuntimeError with a clear message.

Why this matters:
- The training worker script imports these libraries immediately.
- It is better to fail early before starting a multi-GPU job.


3.B Argument parsing (FT.py)
---------------------------
Function: _parse_args()
FT.py defines user-facing flags, such as:

Dataset/model:
- --train_json: path to training dataset JSON (default /users/<USER>/vlm_conversations_train.json)
- --val_json:   path to validation dataset JSON (default /users/<USER>/vlm_conversations_val.json)
- --model_name_or_path: Hugging Face model ID or local path

Outputs:
- --output_dir: folder to save LoRA adapters (and optionally merged model)

Vision/text sizes:
- --img_size (default 490)
- --hd_num   (default 6)
- --max_length (default 8192)

Training hyperparameters:
- --num_train_epochs (default 1)
- --per_device_train_batch_size (default 1)
- --per_device_eval_batch_size  (default 1)
- --gradient_accumulation_steps (default 8)
- --learning_rate, --weight_decay, --warmup_ratio, --lr_scheduler_type

Distributed/launcher behavior:
- --cuda_visible_devices: sets CUDA_VISIBLE_DEVICES for you
- --master_port: torchrun rendezvous port (29501 by default; 0 means “pick a free port”)
- --single_process: do not use torchrun even if multiple GPUs exist
- --no_launch: build/validate everything but do not actually run training

Memory / sharding options:
- --use_deepspeed: pass a DeepSpeed config to Hugging Face Trainer
- --deepspeed_config: choose which DeepSpeed JSON config
- --use_fsdp: use PyTorch FSDP sharding via Trainer (mutually exclusive with DeepSpeed)

Post-processing:
- --save_merged_model: after training, merge LoRA into base and save full model under output_dir/merged_model


3.B.1 Parameter reference (training + LoRA)
------------------------------------------
This section explains the meaning of the parameters that control training.

Important: there are TWO layers of configuration.
1) Launcher layer (FT.py): decides how to launch (single vs multi-GPU) and forwards many flags.
2) Worker/training layer (finetune/finetune.py): defines the real TrainingArguments and LoRA arguments.

3.B.1.1 FT.py launcher parameters (what you type on the command line)
--------------------------------------------------------------------
GPU / distributed launch controls:
- --cuda_visible_devices
  Meaning: sets the environment variable CUDA_VISIBLE_DEVICES for this run.
  Effect: limits which GPUs PyTorch “sees”. If you set "2,3", your process will see 2 GPUs
  numbered as local GPU 0 and 1.

- --master_port
  Meaning: TCP port used by torchrun for process rendezvous on the node.
  Tips:
  - If you launch multiple trainings on the same machine, ports can collide.
  - Use --master_port 0 to auto-pick a free port.

- --single_process
  Meaning: do not use torchrun, even if multiple GPUs are visible.
  Effect: runs a single Python process (typically on GPU 0 only).

- --no_launch
  Meaning: validate everything and print info, but do not start training.
  Use case: quick sanity-check that datasets, helper scripts, and GPUs are visible.

Data / model paths:
- --train_json
  Meaning: path to training JSON.
  Forwarded to finetune.py as: --data_path

- --val_json
  Meaning: path to validation JSON.
  Forwarded to finetune.py as: --eval_data_path

- --model_name_or_path
  Meaning: base model identifier or local folder.
  Example: internlm/internlm-xcomposer2-4khd-7b
  Forwarded to finetune.py as: --model_name_or_path

- --work_dir
  Meaning: where FT.py looks for the helper scripts folder "finetune/".
  Note: this is NOT the output directory; it is just where the worker script lives.

- --output_dir
  Meaning: output folder where adapters/checkpoints are saved.
  Forwarded to finetune.py as: --output_dir

Vision + sequence length controls:
- --img_size
  Meaning: image resolution setting used by the model/dataset.
  Effect in finetune.py:
  - If img_size != 336 it calls model.vit.resize_pos() to adapt vision positional embeddings.
  Effect in data_mix.py:
  - Used to build ImageProcessorHD (normalization + HD_transform).
  Practical note: larger images usually increase GPU memory and runtime.

- --hd_num
  Meaning: controls the “HD_transform” tiling/budget used for images.
  Practical note: larger hd_num generally preserves more detail but increases compute/memory.

- --max_length
  Meaning: maximum token sequence length (context length) used for training.
  Effect in finetune.py:
  - config.max_length is set to this value.
  Practical note: this is one of the biggest drivers of GPU memory. 8192 is expensive.

Training hyperparameters:
- --num_train_epochs
  Meaning: number of passes through the training dataset.
  Practical note: with random sampling inside Mix_dataset, “one epoch” is still defined by
  dataset length, but the exact samples per step are randomized.

- --per_device_train_batch_size
  Meaning: Hugging Face Trainer micro-batch size per GPU process.
  Important caveat for THIS codebase:
  - finetune/data_mix.py already creates a mini-batch inside each dataset item using
    DataArguments.batch_size (default 1).
  - Then Trainer groups multiple dataset items into batches of size per_device_train_batch_size.
  So your effective “real” micro-batch (how many conversations/images are processed together)
  can behave like:
    effective_micro_batch ≈ per_device_train_batch_size * data_args.batch_size
  Because data_args.batch_size is not set by FT.py, it stays at its default (1) unless you
  run finetune.py directly or modify FT.py to pass --batch_size.

- --per_device_eval_batch_size
  Meaning: analogous to per_device_train_batch_size but for evaluation.

- --gradient_accumulation_steps
  Meaning: number of forward/backward passes to accumulate gradients before one optimizer step.
  Effect:
  - Increases effective batch size without increasing peak activation memory as much.
  Approximate effective batch size (ignoring the dataset’s internal batching):
    effective_batch ≈ per_device_train_batch_size * gradient_accumulation_steps * world_size

- --learning_rate
  Meaning: optimizer step size (AdamW by default).
  Practical note: with LoRA you often can use slightly higher LR than full fine-tuning, but it is
  still very task-dependent.

- --weight_decay
  Meaning: L2 regularization applied by AdamW.
  Practical note: helps prevent overfitting; typical values are 0.0 to 0.1.

- --warmup_ratio
  Meaning: fraction of total training steps used for learning-rate warmup.
  Example: 0.01 means “first 1% of steps ramp LR from 0 → learning_rate”.

- --lr_scheduler_type
  Meaning: schedule used to change LR over time.
  Example: cosine means LR decays following a cosine curve after warmup.

- --logging_steps
  Meaning: how often Trainer logs metrics (in steps).

- --save_total_limit
  Meaning: maximum number of checkpoints to keep (older ones deleted).
  Note: FT.py sets save_strategy=epoch, so saving happens once per epoch.

Memory / sharding choices:
- --use_deepspeed
  Meaning: enable DeepSpeed integration in Hugging Face Trainer.
  Effect: passes --deepspeed <config.json> to finetune.py.
  Common result: lower GPU memory usage; potentially slower due to CPU offload.

- --deepspeed_config
  Meaning: path to a DeepSpeed JSON config.
  Defaults to finetune/ds_config_zero2.json.

- --use_fsdp
  Meaning: enable PyTorch FSDP sharding via Trainer.

- --fsdp_policy
  Meaning: FSDP mode string used by TrainingArguments.fsdp.
  Common: "full_shard auto_wrap".

- --fsdp_wrap_cls
  Meaning: transformer layer class name used by Trainer to decide what blocks to wrap.
  Default here: InternLM2DecoderLayer.

Other FT.py-fixed TrainingArguments defaults (FT.py forces these each run):
- --use_lora True
  Meaning: always perform LoRA training (parameter-efficient fine-tuning).

- --save_strategy epoch
  Meaning: checkpoint saving occurs at epoch boundaries.

- --eval_strategy epoch
  Meaning: evaluation occurs at epoch boundaries.
  Note: depending on your Transformers version, the flag may be called
  --evaluation_strategy instead.

- --report_to none
  Meaning: disables reporting to W&B / TensorBoard / etc.

- --gradient_checkpointing True
  Meaning: recompute some activations instead of storing them, reducing memory usage.
  Trade-off: slower training.

- --ddp_find_unused_parameters False
  Meaning: DDP assumes all parameters participate in the forward pass.
  Practical note: can improve speed; if set incorrectly it can error when parameters are unused.

Post-processing:
- --save_merged_model
  Meaning: after training, merge LoRA adapters into a single standalone model folder.
  Output: <output_dir>/merged_model


3.B.1.2 Training parameters in finetune/finetune.py (the actual Trainer knobs)
-----------------------------------------------------------------------------
finetune.py defines dataclasses that map CLI args to structured configuration.

ModelArguments
- model_name_or_path
  Meaning: base model ID or local folder to load.

DataArguments
- data_path
  Meaning: training data JSON path.

- eval_data_path
  Meaning: optional evaluation data JSON path.

- img_size
  Meaning: image size setting passed into dataset preprocessing and model vision adjustments.

- hd_num
  Meaning: the hd_num passed into HD_transform (image tiling/budget control).

- batch_size
  Meaning (IMPORTANT): internal batch size used by Sample_dataset.get_item().
  Default: 1.
  Effect: each dataset item already contains batch_size random samples.
  Interaction: Trainer ALSO batches dataset items using per_device_train_batch_size.
  If you increase both, your effective micro-batch can grow multiplicatively.

- eval_batch_size
  Meaning: analogous to batch_size, but for the eval dataset’s get_item().

TrainingArguments (extends transformers.TrainingArguments)
- output_dir
  Meaning: where to write checkpoints and (for LoRA) adapter files.

- num_train_epochs
  Meaning: how many epochs to train.

- per_device_train_batch_size / per_device_eval_batch_size
  Meaning: Trainer-level micro-batch sizes.

- gradient_accumulation_steps
  Meaning: accumulate gradients over this many steps before an optimizer update.

- learning_rate
  Meaning: AdamW step size.

- weight_decay
  Meaning: AdamW L2 regularization.

- warmup_ratio
  Meaning: warmup fraction.

- lr_scheduler_type
  Meaning: LR schedule type (e.g., cosine).

- bf16 / fp16
  Meaning: enable mixed precision.
  In this setup FT.py chooses bf16 if supported, else fp16.

- gradient_checkpointing
  Meaning: reduces activation memory at the cost of extra compute.

- deepspeed
  Meaning: path to DeepSpeed config JSON (enables DeepSpeed when set).

- fsdp
  Meaning: FSDP mode string (enables FSDP when set).

- fsdp_transformer_layer_cls_to_wrap
  Meaning: which transformer layer class should be wrapped by FSDP auto-wrap.

- max_length
  Meaning: maximum token length (stored into model config as config.max_length).

- optim
  Meaning: which optimizer implementation Trainer uses.
  Default here: adamw_torch.

- cache_dir
  Meaning: optional cache directory for model/tokenizer downloads.

- use_lora
  Meaning: when True, finetune.py freezes base LM weights and injects LoRA adapters.

- fix_vit
  Meaning: when True, freeze the vision encoder (ViT) parameters.
  Default: True (so vision is frozen unless you override).

- fix_sampler
  Meaning: when True, freeze model.vision_proj (vision-to-text projection module).
  Default: True.

- label_names
  Meaning: tells Trainer which keys correspond to labels/inputs.
  In this codebase it is set to ['samples'] so the custom batch structure is passed correctly.


3.B.1.3 LoRA parameters in finetune/finetune.py (LoraArguments)
--------------------------------------------------------------
These parameters control the adapter capacity and where it is applied.

- lora_r
  Meaning: LoRA rank r (adapter “bottleneck” dimension).
  Effect: higher r → more trainable parameters → more capacity but more memory/compute.

- lora_alpha
  Meaning: LoRA scaling factor α.
  Effect: the effective update magnitude is scaled by (α / r).
  Common heuristic: set alpha approximately equal to r.

- lora_dropout
  Meaning: dropout applied on the LoRA branch.
  Effect: regularizes adapters; can help prevent overfitting.

- lora_target_modules
  Meaning: list of module name patterns where adapters are inserted.
  Default targets:
  - 'attention.wqkv' (attention query/key/value projection)
  - 'attention.wo'   (attention output projection)
  - 'feed_forward.w1', 'feed_forward.w2', 'feed_forward.w3' (MLP projections)
  Practical note: these strings must match the base model’s internal module names.

- lora_bias
  Meaning: whether bias parameters are included.
  Implemented options in this code:
  - 'none' (train/save only LoRA weights)
  - 'all'  (include biases too)
  Other values are not implemented here.


3.B.1.4 DeepSpeed JSON parameters (ds_config_zero2.json / ds_config_zero3.json)
------------------------------------------------------------------------------
These files configure how DeepSpeed shards/offloads training state.

Common keys:
- fp16.enabled / bf16.enabled
  Meaning: whether DeepSpeed should use fp16 or bf16.
  In these configs it is "auto", so it follows what Trainer/Accelerate decides.

- zero_optimization.stage
  Meaning: ZeRO optimization stage.
  - Stage 2: shards optimizer states and gradients; parameters are less aggressively partitioned.
  - Stage 3: shards parameters too; can reduce GPU memory further.

- zero_optimization.offload_optimizer
  Meaning: move optimizer state to CPU RAM.
  Keys:
  - device: "cpu" enables CPU offload
  - pin_memory: faster CPU↔GPU transfers

- zero_optimization.offload_param
  Meaning: move (partitioned) parameters to CPU RAM when not actively used.
  Trade-off: saves GPU memory but can slow training.

- gradient_accumulation_steps / gradient_clipping / train_batch_size / train_micro_batch_size_per_gpu
  Meaning: DeepSpeed can infer these from Trainer when set to "auto".

- steps_per_print
  Meaning: how often DeepSpeed prints its own logs.

ZeRO-3-specific keys (in ds_config_zero3.json):
- overlap_comm
  Meaning: overlaps communication with computation to improve throughput.

- contiguous_gradients
  Meaning: stores gradients contiguously for efficiency.

- reduce_bucket_size, stage3_prefetch_bucket_size, stage3_param_persistence_threshold
  Meaning: tuning knobs controlling communication and parameter prefetching.
  Practical note: these are performance/memory tuning settings; most users do not need to change them.


3.C Dataset JSON validation (FT.py)
----------------------------------
Function: _validate_json(path)
FT.py loads the JSON and checks:
- It exists.
- It is a non-empty list.
- First element has keys: "image" and "conversations".
- It warns if the first image path does not exist.

This is intentionally simple validation.
Real errors (bad image paths, malformed conversations, etc.) will still crash later in training.

Expected dataset schema (based on data_mix.py):
Each JSON file is a list of samples. Each sample looks like:

{
  "image": ["/absolute/path/to/img1.png", "/absolute/path/to/img2.png", ...],
  "conversations": [
    {"from": "human", "value": "...user prompt..."},
    {"from": "assistant", "value": "...assistant answer..."},
    ...
  ]
}

Notes:
- "image" is expected to be a list. The code will iterate it.
- The conversation is multi-turn; roles are case-insensitive and mapped to user/assistant.


3.D GPU detection and dtype choice (FT.py)
-----------------------------------------
Function: _gpu_summary()
- Prints CUDA_VISIBLE_DEVICES if set.
- Uses torch.cuda.is_available() and torch.cuda.device_count().
- Prints each GPU name and memory.
- Detects whether bf16 is supported (torch.cuda.is_bf16_supported()).

Then FT.py decides:
- If bf16 supported → it passes --bf16 True to finetune.py
- Else            → it passes --fp16 True

Why this matters:
- Mixed precision reduces memory usage.
- bf16 is generally more stable on newer GPUs.


3.E Required helper files (FT.py)
--------------------------------
Function: _get_finetune_paths(finetune_dir)
FT.py expects these files to already exist:
- finetune/finetune.py
- finetune/ds_config_zero2.json
- finetune/data_mix.py
- finetune/ixc_utils.py

If any are missing, it raises FileNotFoundError.

Important detail:
- FT.py does NOT generate these helper scripts.
- It assumes your workspace already contains them.


3.F Constructing the actual training command (FT.py)
----------------------------------------------------
FT.py builds a list called script_and_args.
This list is effectively the command line that will be executed.

Key parts:
- The “script” is finetune/finetune.py (the worker).
- It forwards dataset paths as:
    --data_path <train_json>
    --eval_data_path <val_json>

- It forwards vision parameters:
    --img_size <img_size>
    --hd_num <hd_num>

- It enables LoRA unconditionally:
    --use_lora True

- It forwards standard Hugging Face TrainingArguments style flags:
    --output_dir <output_dir>
    --num_train_epochs <...>
    --per_device_train_batch_size <...>
    --gradient_accumulation_steps <...>
    --learning_rate <...>
    ...

- It sets some “safety/stability defaults”:
    --save_strategy epoch
    --eval_strategy epoch
    --report_to none
    --gradient_checkpointing True
    --ddp_find_unused_parameters False

About gradient accumulation:
- If per_device_train_batch_size=1 and gradient_accumulation_steps=8
  then the “effective batch size” is ~8 samples per GPU before an optimizer step.
  (In practice, because the dataset code samples batches in a special way, the exact
   meaning depends on how the model consumes “samples”.)


3.G DeepSpeed or FSDP options (FT.py)
------------------------------------
FT.py enforces:
- You cannot set both --use_deepspeed and --use_fsdp.

If --use_deepspeed:
- It chooses a DeepSpeed config JSON:
  - default: finetune/ds_config_zero2.json
  - or: the file passed by --deepspeed_config
- Then it appends:
    --deepspeed <path_to_json>

If --use_fsdp:
- It appends:
    --fsdp <policy string>
    --fsdp_transformer_layer_cls_to_wrap <class name>

DeepSpeed config files explained:
- ds_config_zero2.json: ZeRO stage 2 + CPU offload for optimizer and parameters.
  This reduces GPU memory but can be slower.

- ds_config_zero3.json: ZeRO stage 3 + more aggressive partitioning.
  This can allow larger models/batches to fit by sharding parameters across GPUs.

Both configs set fp16/bf16 to "auto" so they follow your Trainer flags.


3.H Dry run mode (FT.py)
------------------------
If you pass --no_launch:
- FT.py will validate paths and print OK messages.
- It will NOT run training.

This is useful for:
- checking JSON paths
- checking the finetune/ helper scripts exist
- checking GPU visibility


3.I Launching distributed training (FT.py)
-----------------------------------------
FT.py sets a few environment variables before launching:
- CUDA_DEVICE_MAX_CONNECTIONS=1
  (often reduces communication overhead issues)

- PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
  (helps reduce memory fragmentation; can reduce OOM frequency)

It also picks the master port:
- If --master_port 0 → it binds to port 0 to select a free port, then uses that.
- If specified port is busy → it automatically picks a free port and warns.

Then it decides whether to use torchrun:
- If gpu_count > 1 AND not --single_process AND environment does not already specify RANK:
    it launches with:
      python -m torch.distributed.run --nproc_per_node <gpu_count> --master_port <port> finetune.py ...

- Otherwise:
    it runs a single process:
      python finetune.py ...

What torchrun means in practice:
- One Python process is started per GPU.
- Each process receives environment variables like RANK and LOCAL_RANK.
- Hugging Face Trainer reads local_rank to place the model on the correct GPU.


3.J Optional: merging LoRA adapters into a full model (FT.py)
------------------------------------------------------------
If you pass --save_merged_model:
- After training finishes, FT.py calls _merge_lora_to_full_model().

Merge behavior:
1) Load the base model with transformers.AutoModelForCausalLM.from_pretrained(...)
   - trust_remote_code=True (because InternLM-XComposer provides custom modeling code)
   - device_map="auto" (lets Transformers place weights on available GPU(s))
   - dtype: bf16 if supported else fp16

2) Load adapters:
   - model = PeftModel.from_pretrained(base, <output_dir>)

3) Merge adapters into the base weights:
   - merged = model.merge_and_unload()

4) Save merged model to:
   - <output_dir>/merged_model

5) Save tokenizer there too.

Why merge is useful:
- For deployment or inference you can use a single folder without separately specifying adapters.

Why merge is sometimes NOT desired:
- Merged model is much larger on disk.
- Keeping adapters separate is convenient when you want multiple variants.


4) What finetune/finetune.py does (the actual training)
------------------------------------------------------
finetune.py is the worker script executed on each process/GPU.
FT.py is only the launcher.

Main components inside finetune.py:
- Dataclasses defining arguments (ModelArguments, DataArguments, TrainingArguments, LoraArguments)
- Dataset creation (make_supervised_data_module)
- Model loading and freezing
- LoRA injection
- Hugging Face Trainer training loop
- Model saving (special logic to safely save adapters under ZeRO-3)


4.A How finetune.py parses arguments
-----------------------------------
finetune.py uses:
  transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments, LoraArguments))

This maps CLI flags into dataclasses.
Examples:
- --model_name_or_path → ModelArguments.model_name_or_path
- --data_path          → DataArguments.data_path
- --img_size, --hd_num → DataArguments
- --output_dir, --learning_rate, --bf16, --gradient_checkpointing, --deepspeed, ...
  → TrainingArguments (inherits from transformers.TrainingArguments)

LoRA-specific parameters (defaults in LoraArguments):
- lora_r = 64
- lora_alpha = 64
- lora_dropout = 0.05
- lora_target_modules = [
    'attention.wqkv', 'attention.wo',
    'feed_forward.w1', 'feed_forward.w2', 'feed_forward.w3'
  ]
- lora_bias = 'none'

These module names must match the underlying model’s internal layer names.


4.B DeepSpeed detection in finetune.py
--------------------------------------
finetune.py tries to import deepspeed.
If available and training_args.deepspeed is set, it forces:
  training_args.distributed_state.distributed_type = DistributedType.DEEPSPEED

This helps Hugging Face Trainer integrate with DeepSpeed.


4.C Model loading details
------------------------
finetune.py loads configuration:
- config = AutoConfig.from_pretrained(..., trust_remote_code=True)
- config.use_cache = False
  (important because cache + training can break gradient flow and waste memory)
- config.max_length = training_args.max_length

Then loads the model:
- model = AutoModelForCausalLM.from_pretrained(... trust_remote_code=True)
- device_map=None
  (Trainer/Accelerate manages device placement per process)

Then loads tokenizer:
- AutoTokenizer.from_pretrained(... padding_side='right', use_fast=False, trust_remote_code=True)
- attaches tokenizer onto model: model.tokenizer = tokenizer

Important note about trust_remote_code:
- The model repository provides Python code for the architecture.
- That code defines how images are processed and how multimodal inputs are handled.


4.D Vision model behavior (vit resize + freezing)
------------------------------------------------
If data_args.img_size != 336:
- finetune.py calls model.vit.resize_pos()
  (this adjusts positional embeddings to the target resolution)

Then it decides whether to freeze the vision encoder and the vision projection:
- training_args.fix_vit (default True)
  - True  → model.vit.requires_grad_(False) (freeze)
  - False → allow vision encoder training, plus a specific post_layernorm change

- training_args.fix_sampler (default True)
  - True  → model.vision_proj.requires_grad_(False)
  - False → allow it to train

This means: by default, vision-related parts are frozen.
The trainable parameters will come primarily from LoRA adapters inside the language model.


4.E Enabling LoRA in finetune.py
--------------------------------
If training_args.use_lora is True:
1) Freeze the base language model weights:
   for _, param in model.model.named_parameters():
       param.requires_grad = False

2) Create LoRA config:
   lora_config = LoraConfig(
       r=lora_r,
       lora_alpha=lora_alpha,
       target_modules=lora_target_modules,
       lora_dropout=lora_dropout,
       bias=lora_bias,
       task_type='CAUSAL_LM',
   )

3) Wrap model with PEFT:
   model = get_peft_model(model, lora_config)

4) If gradient checkpointing:
   model.enable_input_require_grads()
   (helps checkpointing work correctly with frozen + adapter parameters)

Outcome:
- Only LoRA parameters (and possibly some non-frozen modules if you changed fix_vit/fix_sampler)
  receive gradients and update.


4.F Dataset creation in finetune.py
-----------------------------------
Function: make_supervised_data_module(tokenizer, data_args)

It loads JSON via _load_json():
- Only supports *.json
- Returns a dict mapping filename → loaded list of samples

Then it constructs:
- train_dataset = Mix_dataset(train_json, batch_size=..., img_size=..., hd_num=..., local_rank=...)
- eval_dataset similarly if eval_data_path provided

Then uses a custom collator:
- DataCollatorForSupervisedDataset

The collator returns a batch shaped like:
  { 'samples': {
      'text_input': [...],
      'data_type': [...],
      'image': [...optional...]
    }}

This “samples” key is important because finetune.py sets:
  label_names = ['samples']

Meaning: Trainer will pass the 'samples' structure into the model’s forward() as inputs.


4.G Trainer loop and saving
---------------------------
finetune.py creates:
- trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, ...)

Then:
- trainer.train()
- trainer.save_state()
- safe_save_model_for_hf_trainer(...)

Saving logic (safe_save_model_for_hf_trainer):
- If LoRA and on local_rank==0:
    trainer.model.save_pretrained(output_dir, safe_serialization=True)
    trainer.tokenizer.save_pretrained(output_dir)

- Otherwise, it saves full state_dict (with special handling for DeepSpeed ZeRO-3).

This is critical: without this logic, distributed training (especially ZeRO-3) can save incomplete
weights because parameters are partitioned across ranks.


5) What data_mix.py does (dataset + preprocessing)
-------------------------------------------------
The dataset pipeline here is specialized for multimodal (image + conversation) training.

5.A Conversation formatting: conv2text()
----------------------------------------
conv2text(sources) converts a list of chat turns into a single training string.

Key behavior:
- It uses special tokens:
  END = '[UNUSED_TOKEN_145]\n'
  and prefixes each turn with:
    '[UNUSED_TOKEN_146]user\n'
  or
    '[UNUSED_TOKEN_146]assistant\n'

- It ends the entire conversation with '</s>'

So a conversation becomes a long string like:
  [UNUSED_TOKEN_146]user
  <user text>[UNUSED_TOKEN_145]
  [UNUSED_TOKEN_146]assistant
  <assistant text>[UNUSED_TOKEN_145]
  ...
  </s>

These UNUSED_TOKEN_* tokens are model-specific. The underlying InternLM-XComposer tokenizer/model
expects these tokens to mark role and message boundaries.


5.B ImageProcessorHD (normalization + HD transform)
--------------------------------------------------
ImageProcessorHD:
- Opens image using PIL and converts to RGB.
- Calls HD_transform(image, hd_num=<...>) from ixc_utils.py.
- Converts to tensor and normalizes with CLIP-like mean/std:
  mean = (0.48145466, 0.4578275, 0.40821073)
  std  = (0.26862954, 0.26130258, 0.27577711)

This produces a tensor ready for the model’s vision tower.


5.C Sample_dataset
-----------------
Sample_dataset expects raw_data to be a list of samples (from your JSON).
For one sample i:
- Build conv_text using conv2text(sample['conversations'])
- Read all image paths sample['image']
- For each path, run ImageProcessorHD
- Stack images: torch.stack(images)

So __get_item__ returns:
  {
    'text_input': <string>,
    'image': <Tensor [num_images, C, H, W]>
  }

Then get_item() creates a “batch” by randomly sampling batch_size items:
- It randomly picks indices each time.
- It returns:
  {
    'text_input': [string, string, ...],
    'data_type': 'multi',
    'image': [Tensor, Tensor, ...]
  }

This is not a typical PyTorch dataset pattern: each __getitem__ returns a pre-batched structure.
That is why finetune.py’s collator is custom.


5.D Mix_dataset
---------------
Mix_dataset is a wrapper that can mix multiple datasets.
In this codebase, it receives a dict of {path: loaded_json_list}.

It:
- Creates a Sample_dataset for each loaded list.
- Computes ratios proportional to dataset size.

__getitem__(index):
- On the first call, it sets random.seed(index) once per rank.
  This makes sampling deterministic with respect to the first index seen.
- Selects which dataset to draw from using random.choices(... weights=self.data_ratio)
- Calls ds.get_item() to produce a pre-batched sample
- Returns: { 'samples': <that batch dict> }


6) What ixc_utils.py does (HD image transform)
---------------------------------------------
The key function is HD_transform(img, hd_num).

Goal:
- Resize/pad images in a way that preserves aspect ratio while fitting a “high definition token budget”.

What it does:
1) If width < height, transpose the image (rotate) so width >= height.
2) Compute ratio = width/height.
3) Find an integer "scale" such that:
     scale * ceil(scale/ratio) <= hd_num
   This is a heuristic controlling how many 336x336 “chunks” the image roughly corresponds to.
4) Set new width to scale*336, set new height to keep aspect ratio.
5) Resize the image to [new_h, new_w].
6) Pad height to a multiple of 336 with white padding (255,255,255).
7) If transposed earlier, transpose back.

This helps the vision tower process images at resolutions that are compatible with the model’s
patch/grid expectations.


7) DeepSpeed configs explained
------------------------------
These JSON files are passed to Hugging Face Trainer via the --deepspeed flag.
They configure DeepSpeed’s ZeRO optimization.

7.A ds_config_zero2.json
------------------------
- ZeRO stage 2
- Offloads optimizer state to CPU
- Offloads parameters to CPU
- Many values are "auto" so they are inferred from Trainer arguments

When to use:
- You frequently OOM on GPU even with LoRA.
- You can tolerate slower training.

7.B ds_config_zero3.json
------------------------
- ZeRO stage 3 (more aggressive sharding)
- Also CPU offload, plus overlap_comm, bucket sizes, etc.

When to use:
- You want to split parameters more aggressively across GPUs.
- You want to fit longer sequences, larger images, or larger batches.


8) How to run and what to expect
--------------------------------
Basic run (uses all visible GPUs):
  python /users/<USER>/VLM_finetune/FT.py \
    --output_dir /users/<USER>/outputs/lora_run_001

Dry run:
  python /users/<USER>/VLM_finetune/FT.py --no_launch

Select GPUs:
  python /users/<USER>/VLM_finetune/FT.py --cuda_visible_devices 2,3 --output_dir ...

DeepSpeed ZeRO-2 offload:
  python /users/<USER>/VLM_finetune/FT.py --use_deepspeed --output_dir ...

DeepSpeed ZeRO-3 (example):
  python /users/<USER>/VLM_finetune/FT.py --use_deepspeed \
    --deepspeed_config /users/<USER>/VLM_finetune/finetune/ds_config_zero3.json \
    --output_dir ...

Save merged model after training:
  python /users/<USER>/VLM_finetune/FT.py --save_merged_model --output_dir ...


9) Outputs: what gets written to disk
------------------------------------
In --output_dir (for LoRA runs), you should expect:
- adapter_config.json
- adapter_model.safetensors
- tokenizer files (because finetune.py saves them when LoRA is enabled)
- trainer_state.json
- possibly checkpoint-* directories (depending on Trainer save strategy)

If --save_merged_model:
- <output_dir>/merged_model/ will contain a full model suitable for direct loading with Transformers,
  plus tokenizer.


10) Common failure modes and what they mean
-------------------------------------------
10.1 "Dataset json not found" or "Unexpected sample format"
- Your --train_json/--val_json path is wrong.
- Or your JSON isn’t a list of samples with keys: image, conversations.

10.2 Warnings about missing image paths
- FT.py only checks the FIRST sample.
- If any image path is missing later, data_mix.py will crash when PIL tries to open it.

10.3 CUDA OOM
- Common when max_length=8192 and/or large images.
- Mitigations:
  - reduce --max_length (4096 or 3072)
  - reduce --img_size (336) and --hd_num (4)
  - enable --use_deepspeed
  - reduce gradient_accumulation_steps

10.4 "You are using a model of type internlmxcomposer2 to instantiate a model of type internlm2"
- This comes from model code/config interactions inside Transformers.
- Usually it still runs; if it becomes an error, it indicates an incompatibility between model code
  and Transformers version.


11) Minimal mental model (end-to-end summary)
--------------------------------------------
If you want a single short explanation:

- FT.py validates your environment and data paths, detects GPUs, then launches finetune.py with
  consistent settings.

- finetune.py loads the InternLM-XComposer2 multimodal model and tokenizer, freezes most weights,
  injects LoRA adapters into specific transformer submodules, builds a dataset that turns
  (image paths + multi-turn conversations) into tensors + text strings, then trains using
  Hugging Face Trainer (optionally with DeepSpeed/FSDP).

- The output is primarily LoRA adapter weights, which can be applied on top of the base model.
  Optionally, FT.py merges adapters into a standalone model folder.


Appendix A: What script_conda.sh is for (not required by FT.py)
--------------------------------------------------------------
script_conda.sh is a helper to install a conda distribution (anaconda/miniconda/miniforge)
into a chosen prefix and set up large cache directories to avoid filling the root disk.

FT.py does not execute it automatically; it is just a setup utility.


Appendix B: FINETUNE_GUIDE.txt
------------------------------
FINETUNE_GUIDE.txt is a short runbook that matches FT.py’s intended usage:
- create/activate conda env
- install torch/transformers/peft
- run FT.py --no_launch
- run FT.py normally
- optionally enable DeepSpeed/FSDP
- optionally merge model

This detailed guide expands that quick guide into the full “how it works” explanation.