Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / vlm_trainer.py: 67%
214 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2025-2026 Bytedance Ltd. and/or its affiliates
2# Copyright 2026 Huawei Technologies Co., Ltd
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""VLM Trainer assembled from the shared BaseTrainer stages."""
17__all__ = ["VLMTrainer"]
19from collections import defaultdict
20from itertools import count, repeat
21from typing import Any, Dict, Iterator, Optional
23import torch
25from hyper_parallel.data.batching import calculate_num_micro_batches
26from hyper_parallel.data.batching.get_batch import OmniParallelBatch
27from hyper_parallel.data.omni import OmniDataTransform
28from hyper_parallel.data.omni.metadata import vlm_sample_metadata
29from hyper_parallel.distributed.encoder_parallel import build_encoder_parallel_runtime
30from hyper_parallel.distributed.encoder_parallel.transport import EncoderParallelBatchTransport
31from hyper_parallel.models.registry import resolve_model_adapter
32from hyper_parallel.trainer.runtime.loss_aggregation import count_loss_token
33from hyper_parallel.trainer.runtime.logging import create_logger
34from hyper_parallel.trainer.runtime.memory import print_device_mem_info
35from hyper_parallel.trainer.runtime.memory_profiler import memory_profiler
36from hyper_parallel.trainer.runtime.worker_recovery import (
37 recovery_constructor,
38 recovery_epoch_initialized,
39 recovery_train_loop,
40 recovery_train_step,
41)
42from hyper_parallel.trainer.runtime.device import synchronize # pylint: disable=syntax-error
43from hyper_parallel.trainer.base import BaseTrainer
44from hyper_parallel.data.distributed import DistributedDataLoader
45from hyper_parallel.trainer.config import TrainerConfig
47logger = create_logger(__name__)
50class VLMTrainer:
51 """Compose the VLM training runtime from explicit BaseTrainer stages."""
53 base: BaseTrainer
55 @recovery_constructor
56 def __init__(self, config: TrainerConfig) -> None:
57 """Build the VLM Trainer in the same explicit order as VeOmni."""
58 self.base = BaseTrainer.__new__(BaseTrainer)
59 self.base.config = config
61 self.base._setup()
62 memory_profiler.reset(
63 self.base.config.memory,
64 global_rank=self.base.global_rank,
65 tp_rank=self.base.mesh.tp_rank,
66 dp_rank=self.base.mesh.dp_rank,
67 )
68 self.base._build_model()
69 self.base._build_loss()
71 # datasets
72 self._build_model_assets()
73 self._build_data_transform()
74 self.base._build_dataset()
76 # dataloader
77 self._build_collate_fn()
78 self.base._build_dataloader(metadata_fn=vlm_sample_metadata)
80 # get_batch
81 self._build_get_batch()
82 self.base.attach_model_integration_data_pipeline()
83 self.base._compute_train_iters()
85 self.base._build_optimizer()
86 self.base.model_integration.attach_optimizer(self.base.optimizer)
87 self.base._build_lr_scheduler()
88 self.base._build_training_context()
89 self.base._init_callbacks()
91 def _build_model_assets(self) -> None:
92 """Build and publish the processor consumed by the Omni transform."""
93 config: TrainerConfig = self.base.config
94 if config.dataset is None:
95 raise ValueError("dataset must define a build target")
97 # The model-owned processor is built through the Omni ``model_assets``
98 # target; forward the model's ``trust_remote_code`` flag so a natively
99 # registered architecture such as the Kimi-K2.6 family (``kimi_k26``)
100 # stays on the local implementation unless the config opts into remote
101 # code.
102 processor = config.dataset.model_assets.build(
103 trust_remote_code=bool(
104 getattr(config.model, "trust_remote_code", True)
105 ),
106 )
107 tokenizer = getattr(processor, "tokenizer", None)
108 if tokenizer is None:
109 raise ValueError("dataset.model_assets must build a processor with a tokenizer")
111 self.base.processor = processor
112 self.base.tokenizer = tokenizer
113 self.base.chat_template = getattr(processor, "chat_template", None)
114 self.base.model_assets = [self.base.model_config, processor]
116 def _build_data_transform(self) -> None:
117 """Build the Omni encoding lifecycle from the prebuilt processor."""
118 dataset_config = self.base.config.dataset
119 if dataset_config is None:
120 raise ValueError("dataset must define a build target")
122 if dataset_config.data_transform is None:
123 raise ValueError("dataset.data_transform must define an Omni transform build target")
125 if dataset_config.training_mode is None:
126 raise ValueError("dataset.training_mode must be explicitly set to 'sft' or 'pretrain' for VLM training")
128 data_transform = dataset_config.data_transform.build(
129 processor=self.base.processor,
130 training_mode=dataset_config.training_mode,
131 max_seq_len=dataset_config.data_config["max_seq_len"],
132 )
133 if not isinstance(data_transform, OmniDataTransform):
134 raise TypeError("dataset.data_transform must build an OmniDataTransform")
136 self.base.data_transform = data_transform
138 def _build_collate_fn(self) -> None:
139 """Build the VLM collator and gradient-accumulation batch count."""
140 dataloader_config = self.base.config.dataloader
142 if dataloader_config is None or dataloader_config.collate_fn is None:
143 raise ValueError("dataloader.collate_fn must define a build target")
145 training_config = self.base.config.training
146 self.base.num_micro_batches = calculate_num_micro_batches(
147 global_batch_size=training_config.global_batch_size,
148 micro_batch_size=training_config.micro_batch_size,
149 dp_world_size=self.base.mesh.dp_size,
150 )
151 max_seq_len = self.base.config.dataset.data_config["max_seq_len"]
153 self.base.collate_fn = dataloader_config.collate_fn.build(
154 mesh_context=self.base.mesh,
155 max_seq_len=max_seq_len,
156 )
158 def _build_get_batch(self) -> None:
159 """Build the DataLoader-to-LLM batch runtime."""
160 config = self.base.config
162 if config.dataloader.get_batch is None:
163 raise ValueError("dataloader.get_batch must define a batching runtime target")
165 if getattr(config.dataloader.get_batch, "encoder_parallel", None) is not None:
166 raise ValueError("encoder_parallel belongs under accelerator, not dataloader.get_batch")
168 encoder_runtime = build_encoder_parallel_runtime(
169 config=config.accelerator.encoder_parallel,
170 mesh_context=self.base.mesh,
171 model=self.base.model,
172 model_adapter_spec=resolve_model_adapter(self.base.model),
173 execution_options={
174 "micro_batch_size": int(config.training.micro_batch_size),
175 "compile_enabled": bool(config.compile.enabled),
176 "validate_placement": bool(getattr(config.model, "validate_placement", False)),
177 },
178 )
179 get_batch = config.dataloader.get_batch.build(
180 mesh_context=self.base.mesh,
181 dataloader_context=self.base.dataloader_context,
182 device=self.base.device,
183 data_config=getattr(config.dataset, "data_config", {}),
184 pp_shared_data=bool(getattr(config.dataloader, "pp_shared_data", False)),
185 )
187 if encoder_runtime is not None:
188 if not isinstance(get_batch, OmniParallelBatch):
189 raise ValueError("encoder parallel requires OmniParallelBatch")
191 get_batch.batch_transport = EncoderParallelBatchTransport(runtime=encoder_runtime)
193 self.base.get_batch = get_batch
195 @property
196 def distributed_setup(self) -> Any:
197 """Return the shared distributed setup."""
198 return self.base.distributed_setup
200 @property
201 def mesh(self) -> Any:
202 """Return the shared mesh context."""
203 return self.base.mesh
205 @property
206 def dp_cp_mesh(self) -> Any:
207 """Return the shared data/context-parallel mesh."""
208 return self.base.dp_cp_mesh
210 def on_train_begin(self) -> None:
211 """Dispatch the training-begin lifecycle hook."""
212 self.base.on_train_begin()
214 def on_train_end(self) -> None:
215 """Dispatch the training-end lifecycle hook."""
216 self.base.on_train_end()
218 def on_epoch_begin(self) -> None:
219 """Dispatch the epoch-begin lifecycle hook."""
220 self.base.on_epoch_begin()
222 def on_epoch_end(self) -> None:
223 """Dispatch the epoch-end lifecycle hook."""
224 self.base.on_epoch_end()
226 def on_step_begin(self) -> None:
227 """Dispatch the step-begin lifecycle hook."""
228 self.base.on_step_begin()
230 def on_micro_step_begin(self, micro_batch: dict[str, Any]) -> None:
231 """Dispatch the micro-step-begin lifecycle hook.
233 Args:
234 micro_batch: Prepared inputs and lightweight metric metadata.
235 """
236 self.base.on_micro_step_begin(micro_batch)
238 def on_micro_step_end(self, loss_dict: dict[str, torch.Tensor]) -> None:
239 """Dispatch the micro-step-end lifecycle hook.
241 Args:
242 loss_dict: Named losses and metrics from the completed forward-backward step.
243 """
244 self.base.on_micro_step_end(loss_dict)
246 def on_step_end(
247 self,
248 loss: Any = None,
249 loss_dict: Any = None,
250 grad_norm: Any = None,
251 ) -> None:
252 """Dispatch the step-end lifecycle hook.
254 Args:
255 loss: Aggregate step loss.
256 loss_dict: Named step losses.
257 grad_norm: Measured gradient norm.
258 """
259 self.base.on_step_end(
260 loss=loss,
261 loss_dict=loss_dict,
262 grad_norm=grad_norm,
263 )
265 def forward_backward_step(
266 self,
267 data_iterator: Any,
268 ) -> tuple[torch.Tensor, Dict[str, torch.Tensor]]:
269 """Fetch and execute one forward-backward micro-step.
271 Args:
272 data_iterator: Iterator providing one multimodal batch per call.
274 Returns:
275 Loss tensor and named loss tensors for this FB step.
276 """
277 model_inputs, loss_inputs = self.base.get_batch(data_iterator)
278 self.base.current_token_counts = count_loss_token(loss_inputs)
279 self.on_micro_step_begin(model_inputs)
280 loss, loss_dict = self.base.forward_backward_step(model_inputs, loss_inputs)
281 self.on_micro_step_end(loss_dict)
283 return loss, loss_dict
285 @recovery_train_step
286 def train_step(self, data_iterator: Any) -> Dict[str, float]:
287 """Execute one VLM training step.
289 Args:
290 data_iterator: Iterator providing multimodal micro-batches.
292 Returns:
293 Aggregated loss and gradient norm.
294 """
295 memory_profiler.step()
296 num_micro_steps = self.base.num_micro_batches
297 self.base.begin_loss_step()
299 self.on_step_begin()
300 self.base.model_integration.begin_step(self.base.state.global_step + 1)
301 synchronize()
303 total_loss = 0.0
304 total_loss_dict = defaultdict(int)
306 if getattr(self.base.model, "_hp_pipeline_partition", None) is not None:
307 if self.base.config.pipeline.schedule == "mpipe":
308 # Full MPipe transpose distributes microbatches round-robin within the PP group.
309 def _read_microbatch(index: int) -> tuple[dict, dict]:
310 return self.base.get_batch(data_iterator, mpipe_owner=index % self.base.mesh.pp_size)
312 # map propagates loader exhaustion to _train_epoch when the final step is incomplete.
313 batches = map(_read_microbatch, range(num_micro_steps))
314 else:
315 batches = map(self.base.get_batch, repeat(data_iterator, num_micro_steps))
316 total_loss, total_loss_dict = self.base.pipeline_forward_backward(batches, num_micro_steps)
317 else:
318 for micro_step in range(num_micro_steps):
319 self.base.model_reshard(micro_step, num_micro_steps)
320 self.base.configure_fsdp_gradient_sync(
321 micro_step,
322 num_micro_steps,
323 )
324 self.base.begin_fsdp_runtime_diagnostics(micro_step)
325 loss, loss_dict = self.forward_backward_step(
326 data_iterator,
327 )
329 total_loss += loss.item()
330 for loss_name, loss_value in loss_dict.items():
331 total_loss_dict[loss_name] += loss_value.item()
333 total_loss, grad_norm = self.base.prepare_optimizer_step(total_loss, total_loss_dict)
334 self.base.step_optimizers_and_schedulers()
336 # Checkpoint and logging callbacks observe completed optimizer updates.
337 self.base.state.global_step += 1
338 grad_norm_value = float(grad_norm)
339 # The base trainer owns this integration hook and the VLM subclass only
340 # mirrors the base step order, so reaching the private method is intended.
341 self.base._end_model_integration_step( # pylint: disable=protected-access
342 {"loss": total_loss, "grad_norm": grad_norm_value}
343 )
344 self.on_step_end(
345 loss=total_loss,
346 loss_dict=total_loss_dict,
347 grad_norm=grad_norm_value,
348 )
350 step_metrics = {
351 "loss": total_loss,
352 "grad_norm": grad_norm_value,
353 }
354 return step_metrics
356 @recovery_epoch_initialized
357 def _create_data_iterator(self) -> Optional[Iterator[Any]]:
358 """Construct the native iterator before consuming this epoch's data."""
359 loader = self.base.train_dataloader
360 return iter(loader) if loader is not None else None
362 def _train_epoch(self, epoch: int, balanced_loader: bool) -> bool:
363 """Run complete optimizer steps and report actual Dataset exhaustion."""
364 data_iterator = self._create_data_iterator()
365 start_step = self.base.state.global_step - epoch * self.base.train_steps
366 train_steps = min(self.base.train_steps, self.base.train_iters - epoch * self.base.train_steps)
368 if balanced_loader:
369 start_step = 0
370 train_steps = self.base.train_iters - self.base.state.global_step
372 for _ in range(start_step, train_steps):
373 try:
374 self.train_step(data_iterator)
375 except StopIteration:
376 optimizers = self.base.optimizer
377 for optimizer in optimizers if isinstance(optimizers, list) else [optimizers]:
378 optimizer.zero_grad()
379 logger.info(
380 "epoch:%s Dataloader finished with drop_last %s", epoch, self.base.config.dataloader.drop_last
381 )
382 return True
384 return False
386 @recovery_train_loop
387 def train(self) -> None:
388 """Run the VLM training loop."""
389 try:
390 self.on_train_begin()
391 logger.info(
392 "Rank%s Start training. Global step: %s. Train iters: %s. Start epoch: %s. Train epochs: %s.",
393 self.base.local_rank,
394 self.base.state.global_step,
395 self.base.train_iters,
396 self.base.state.epoch,
397 self.base.train_epochs,
398 )
400 train_dataloader = self.base.train_dataloader
401 balanced_loader = isinstance(train_dataloader, DistributedDataLoader)
402 start_epoch = self.base.state.epoch
403 epochs = count(start_epoch) if balanced_loader else range(start_epoch, self.base.train_epochs)
404 for epoch in epochs:
405 if self.base.state.global_step >= self.base.train_iters:
406 break
408 # Do not erase the cursor restored by on_train_begin on the first epoch.
409 if train_dataloader is not None and (not balanced_loader or epoch != start_epoch):
410 train_dataloader.set_epoch(epoch)
412 self.base.state.epoch = epoch
413 self.on_epoch_begin()
414 epoch_start_step = self.base.state.global_step
415 epoch_exhausted = self._train_epoch(epoch, balanced_loader)
417 if balanced_loader and epoch != start_epoch and self.base.state.global_step == epoch_start_step:
418 raise ValueError("VLM Dataset epoch cannot provide one complete optimizer step")
420 self.on_epoch_end()
421 self.base.state.epoch = epoch + 1 if not balanced_loader or epoch_exhausted else epoch
422 print_device_mem_info(f"VRAM usage after epoch {epoch + 1}")
424 memory_profiler.stop()
425 self.on_train_end()
427 except BaseException:
428 try:
429 memory_profiler.stop()
430 # Snapshot export must preserve the training error even if interrupted.
431 except BaseException: # pylint: disable=broad-exception-caught
432 logger.exception("Failed to save memory snapshot after training error.")
433 finally:
434 self.base.abort_profilers()
435 raise
437 if balanced_loader:
438 try:
439 train_dataloader.wait_for_prefetch()
440 finally:
441 train_dataloader.close()
443 synchronize()
444 self.base.destroy_distributed()