Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/losses/aux_loss.py 100%  
hyper_parallel/components/losses/chunked_cross_entropy.py 88.9% 321
hyper_parallel/core/optimizer/optimizer.py 100%  
hyper_parallel/core/pipeline_parallel/_stage.py 100%  
hyper_parallel/core/pipeline_parallel/mpipe/schedule.py 50.0% 202-203
hyper_parallel/core/utils/clip_grad.py 69.2% 1047-1053,1153
hyper_parallel/data/batching/build_dataloader.py 25.0% 502-504,508-510,514-516,520-522
hyper_parallel/data/batching/get_batch.py 26.7% 81,124-133
hyper_parallel/data/parallel/batch_parallel.py 4.8% 474-476,478-481,483,485-488,491-498
hyper_parallel/distributed/_builder/parameter_sharding.py 66.7% 60,137-138
hyper_parallel/distributed/mesh.py 68.8% 351-352,355-357
hyper_parallel/trainer/base.py 18.0% 401-411,417,426,430-436,448-449,486-487,1151-1153,1282,1388-1389,1391,1394-1397,1401-1403,1405-1407
hyper_parallel/trainer/callbacks/environ_meter_callback.py 94.4% 232
hyper_parallel/trainer/callbacks/moe_monitor_callback.py 100%  
hyper_parallel/trainer/config/trainer.py 87.0% 112,115,118
hyper_parallel/trainer/runtime/pipeline.py 13.5% 39-41,45-48,52-71,74,85-106,114-123,125,129-135,148-154,156-165,174-193,196,200-225,234-239,241,244-257,259-265
hyper_parallel/trainer/text_trainer.py 81.8% 309-310
hyper_parallel/trainer/vlm_trainer.py 100%  
hyper_parallel/components/losses/chunked_cross_entropy.py
317
318
319
320
321
322
323
324
325
        """
        # Token aggregation and the model objective must count the same labels.
        partition = self._validate_distributed_contract(model, distributed_setup)
        if partition is not None and not partition.is_last:
            return
        if getattr(model, "supports_chunked_loss", False):
            head = getattr(model, "lm_head", None)
            if not getattr(head, "supports_chunked_cross_entropy", False):
                raise TypeError("native chunked models must own a compatible terminal head")
hyper_parallel/core/pipeline_parallel/mpipe/schedule.py
198
199
200
201
202
203
204
205
206
207
            )
        stages = self._check_stages(stages)
        for stage in stages:
            for scheduler in stage.all_hsdp_schedulers:
                if owner_backward or scheduler.mesh is None or scheduler.mesh.size() != 1:
                    raise ValueError("MPipe HSDP stages require singleton meshes and stage-zero prefix backward")
        self._overflow_mode = overflow_mode
        # ``preprocess_module`` is the resolved block to transpose (first T text
        # layers, the visual tower, or a param-free identity for dataload-only).
        self._preprocess_module = preprocess_module
hyper_parallel/core/utils/clip_grad.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057


def _reduce_pipeline_norm(norm: torch.Tensor, norm_type: float, group: object) -> torch.Tensor:
    """Combine norms of disjoint stages on the group's communication device."""
    if math.isinf(norm_type):
        op = dist.ReduceOp.MAX if norm_type > 0 else dist.ReduceOp.MIN
        return _all_reduce_offloaded(norm, op, group)
    if norm_type == 0:
        return _all_reduce_offloaded(norm, dist.ReduceOp.SUM, group)
    power_sum = _all_reduce_offloaded(norm.pow(norm_type), dist.ReduceOp.SUM, group)
    return power_sum.pow(1.0 / norm_type)


def _check_finite_norm(total_norm: torch.Tensor, norm_type: float) -> None:
    """Reject a non-finite global norm before using it to scale gradients."""
1149
1150
1151
1152
1153
1154
1155
1156
        norm_grads, key_per_grad,
    )

    if pp_group is not None:
        total_norm = _reduce_pipeline_norm(total_norm, norm_type, pp_group)

    if error_if_nonfinite:
        _check_finite_norm(total_norm, norm_type)
hyper_parallel/data/batching/build_dataloader.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        del epoch

    def wait_for_prefetch(self) -> None:
        """Drain source prefetch work when the wrapped loader supports it."""
        wait = getattr(self.source_dataloader, "wait_for_prefetch", None)
        if callable(wait):
            wait()

    def prefetch(self) -> None:
        """Start source prefetch when the wrapped loader supports it."""
        prefetch = getattr(self.source_dataloader, "prefetch", None)
        if callable(prefetch):
            prefetch()

    def prefetch_plan(self) -> None:
        """Run the source pipeline prefetch plan when available."""
        prefetch_plan = getattr(self.source_dataloader, "prefetch_plan", None)
        if callable(prefetch_plan):
            prefetch_plan()

    def close(self) -> None:
        """Close the wrapped loader when it owns closeable resources."""
        close = getattr(self.source_dataloader, "close", None)
        if callable(close):
            close()

    def state_dict(self) -> dict[str, Any]:
        """Save repeat progress and source loader state."""
        checkpoint_state = {
hyper_parallel/data/batching/get_batch.py
77
78
79
80
81
82
83
84
85
        if runtime_input_adapter is not None and not isinstance(runtime_input_adapter, RuntimeInputAdapter):
            raise TypeError("OmniParallelBatch runtime_input_adapter must be a RuntimeInputAdapter")

        if pp_shared_data:
            raise NotImplementedError("OmniParallelBatch does not support pp_shared_data")
        # Each PP coordinate reads the same deterministic DP sample stream;
        # TP broadcast and CP slicing remain local to that physical stage.

        source_config = data_config or {}
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
            if not isinstance(source_batch, Mapping):
                raise TypeError("Omni DataLoader must yield a mapping batch")

            if self.mpipe_mesh is not None:
                if mpipe_owner is None:
                    raise ValueError("MPipe batch requires its visual owner rank")
                fields = None
                pixels = None
                if self.mpipe_mesh.get_local_rank() == mpipe_owner:
                    fields = dict(source_batch)
                    pixels = fields.pop("pixel_values", None)
                source_batch = broadcast_batch_mapping(fields, self.mpipe_mesh.get_group(), mpipe_owner, self.device)
                if pixels is not None:
                    source_batch["pixel_values"] = pixels
            normalized_batch = self._normalize_source_batch(source_batch)
            local_batch = self.cp_sharder.shard(normalized_batch)
            logger.debug(
                "Omni get_batch: batch=%d source_ready global_shape=%s local_shape=%s tp=%d cp=%d cp_rank=%d",
hyper_parallel/data/parallel/batch_parallel.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
        group: Consumer process group.
        source_rank: Source index within the group.
        device: Target tensor device.
    """
    is_source = dist.get_rank(group) == source_rank
    if is_source:
        parallel_batch = {name: value.to(device, non_blocking=True) if torch.is_tensor(value) else value
                          for name, value in batch.items()}
        metadata = []
        for name, value in parallel_batch.items():
            if torch.is_tensor(value):
                metadata.append((name, tuple(value.shape), value.dtype, None))
            else:
                metadata.append((name, None, None, value))
    else:
        parallel_batch = {}
        metadata = None
    object_list = [metadata]
    dist.broadcast_object_list(
        object_list, group=group, group_src=source_rank, device=device
    )
    for name, shape, dtype, value in object_list[0]:
        if shape is None:
            parallel_batch[name] = value
            continue
        if not is_source:
            parallel_batch[name] = torch.empty(shape, dtype=dtype, device=device)
        dist.broadcast(parallel_batch[name], group=group, group_src=source_rank)
    return parallel_batch
hyper_parallel/distributed/_builder/parameter_sharding.py
56
57
58
59
60
61
62
63
    """Fetch an attribute along a dotted FQN (numeric segments index into ModuleLists)."""
    obj = model
    for part in fqn.split(".") if fqn else ():
        if part.isdigit() and not isinstance(obj, nn.Module):
            obj = obj[int(part)]
        else:
            obj = getattr(obj, part)
    return obj
133
134
135
136
137
138
139
140
141
142
        if excluded and name.startswith(excluded):
            continue
        if isinstance(param, DTensor):
            saved.append((name, param))
            parent, _, leaf = name.rpartition(".")
            owner = _get_attr_by_path(module, parent)
            owner._parameters[leaf] = param.to_local()  # pylint: disable=protected-access
    try:
        yield
    finally:
hyper_parallel/distributed/mesh.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    def _stage_mesh(self, kwargs: dict[str, Any]) -> Any:
        """Create every stage's group in the same order before selecting the local tile."""
        if not kwargs["init_backend"] or self.pp_size == 1:
            return _init_topology_mesh(kwargs)
        names = kwargs["mesh_dim_names"]
        root = _init_topology_mesh({
            **kwargs, "mesh_shape": (self.pp_size, *kwargs["mesh_shape"]), "mesh_dim_names": ("pp", *names),
        })
        if self.pp_mesh is None:
            self.pp_mesh = root["pp"]
        return root[names]

    def _build_expert_parallel_mesh(self, device_type: str, init_backend: bool) -> None:
        """Build the expert-parallel FSDP mesh when expert parallelism is enabled."""
        self.fsdp_moe_mesh = None
hyper_parallel/trainer/base.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
            save_configs(self.config, self.config.checkpoint.checkpoint_dir)

    def _combine_pipeline_chunks(self, build: Callable) -> torch.nn.Module:
        """Build the remaining virtual stages and register the rank's training parameters."""
        local_count = self.config.pipeline.local_stage_count
        if local_count == 1 and self.config.pipeline.schedule != "mpipe":
            return self.model
        spec = resolve_model_adapter(self.model).pipeline_parallel()
        if spec.combine_chunks is None:
            raise ValueError("The model pipeline adapter must support virtual chunks for interleaved training")
        parts = [self.model]
        for index in range(1, local_count):
            setup = replace(self.distributed_setup, pipeline_chunk_index=index)
            parts.append(build(distributed_setup=setup))
        return spec.combine_chunks(tuple(parts), self.mesh.pp_mesh.get_group())

    def _build_model(self) -> None:
        """Build the model and derive Trainer-owned runtime state."""
        self.peft_config = self.config.peft
413
414
415
416
417
418
419
420
421
    def _build_model(self) -> None:
        """Build the model and derive Trainer-owned runtime state."""
        self.peft_config = self.config.peft
        ops.set_backends(getattr(self.config, "ops", {}))
        build = partial(
            self.config.model.build,
            peft_config=self.peft_config,
            activation_checkpoint=self.config.activation_checkpoint,
            compile_config=self.config.compile,
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
            # The final dtype is applied inside the atomic build (05 stage-5
            # item 5); the Trainer no longer patches it afterwards.
            model_init_dtype=self.config.model_init_dtype,
        )
        self._finalize_model_build(build)

    def _finalize_model_build(self, build: Callable) -> None:
        """Validate parameter dtypes and derive Trainer-owned model runtime state."""
        if self.config.pipeline.schedule == "mpipe" and self.mesh.dp_size != 1:
            raise ValueError("MPipe currently requires DP1 for variable-image visual FSDP execution")
        self.model = build(distributed_setup=self.distributed_setup)
        if self.config.accelerator.pp_size > 1 and not self.config.compile.selects_graph_compiler():
            if getattr(self.model, "_hp_pipeline_partition", None) is None:
                raise ValueError("Eager Trainer PP requires a model factory that installs a pipeline partition")
            self.model = self._combine_pipeline_chunks(build)
        _validate_optimize_dtype(
            self.model,
            fp32_main_params=self.config.optimizer.fp32_main_params,
        )
444
445
446
447
448
449
450
451
452
453
                "Model config:\n%s",
                json.dumps(self.model.config.to_dict(), indent=2),
            )
        if self.config.accelerator.loss_parallel:
            for part in getattr(self.model, "parts", (self.model,)):
                part.loss_function = causal_lm_loss_parallel
        model_parts = getattr(self.model, "parts", None)
        self.model_parts = list(model_parts) if model_parts is not None else [self.model]
        self.hsdp_model_parts = [
            model_part
482
483
484
485
486
487
488
489
490
491
        # ordinary forward materializes an otherwise avoidable output tensor.
        loss_model_binding_hook = getattr(self.loss_fn, "bind_model", None)

        if callable(loss_model_binding_hook):
            for part in getattr(self.model, "parts", (self.model,)):
                loss_model_binding_hook(part, self.distributed_setup)

    def _build_model_assets(self) -> None:
        """Require a concrete Trainer to build modality-specific model assets."""
        raise NotImplementedError("Concrete Trainer must implement _build_model_assets")
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
        Args:
            batches: Model and loss inputs for the local data-parallel replica.
            count: Number of microbatches to schedule.
        """
        if self.pipeline_runtime is None:
            self.pipeline_runtime = TrainerPipeline(self)
        return self.pipeline_runtime.run(batches, count)

    def model_reshard(self, micro_step: int, num_micro_steps: int) -> None:
        """Reshard model after backward pass; policy lives in ``runtime/fsdp.py``.
1278
1279
1280
1281
1282
1283
1284
1285
1286
        post_clip_norm = None
        compiler = getattr(self, "graph_compiler", None)
        clip_kwargs = {"parameter_layouts": compiler.parameter_layouts} if compiler is not None else {}
        if self.pipeline_runtime is not None:
            clip_kwargs["pp_group"] = self.mesh.pp_mesh.get_group()
        if max_grad_norm > 0:
            grad_norm = clip_grad_norm_(self.model, max_grad_norm, **clip_kwargs)

            if self.model_integration.runtime_enabled:
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410

        # token num for fixed_ce_loss in postforward
        self.begin_loss_step()
        num_micro_steps = len(micro_batches)
        if getattr(self.model, "_hp_pipeline_partition", None) is not None:
            batches = ((batch, {name: batch[name] for name in ("labels", "shift_labels", "loss_mask")
                                if name in batch}) for batch in micro_batches)
            total_loss, total_loss_dict = self.pipeline_forward_backward(batches, num_micro_steps)
        else:
            # forward and backward pass with gradient_accumulationsteps
            for micro_step, micro_batch in enumerate(micro_batches):
                self.model_reshard(micro_step, num_micro_steps)
                self._configure_fsdp_gradient_sync(micro_step, num_micro_steps)
                self.begin_fsdp_runtime_diagnostics(micro_step)
                loss: torch.Tensor
                loss_dict: Dict[str, torch.Tensor]
                # token num for fixed_ce_loss in postforward
                self.current_token_counts = count_loss_token(micro_batch)
                loss, loss_dict = self.forward_backward_step(micro_batch)
                self.on_micro_step_end(loss_dict)

                total_loss += loss.item()
                for k, v in loss_dict.items():
                    total_loss_dict[k] += v.item()

        total_loss, grad_norm = self.prepare_optimizer_step(total_loss, total_loss_dict)
        self.step_optimizers_and_schedulers()
hyper_parallel/trainer/callbacks/environ_meter_callback.py
228
229
230
231
232
233
234
235
236
        mesh = getattr(self.trainer, "mesh", None)
        pp_mesh = getattr(mesh, "pp_mesh", None)
        if get_world_size_safe() <= 1 or int(getattr(mesh, "pp_size", 1)) <= 1 or pp_mesh is None:
            return float(value)
        return float(all_reduce(value, op="max", group=pp_mesh.get_group()))

    @staticmethod
    def _accumulate_scalar(current: Any, value: Any) -> Any:
        """Add one batch scalar to a running per-step total.
hyper_parallel/trainer/config/trainer.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    def _validate_pipeline(self) -> None:
        """Validate eager pipeline schedules, topology, and checkpoint export."""
        graph_mode = self.compile.selects_graph_compiler()
        if self.compile.enabled and not graph_mode and self.accelerator.pp_size > 1:
            raise ValueError("compile is not supported together with pipeline parallelism")
        eager_pipeline = self.accelerator.pp_size > 1 and not graph_mode
        if self.pipeline.schedule in ("interleaved_1f1b", "mpipe") and not eager_pipeline:
            raise ValueError(f"{self.pipeline.schedule} requires eager Trainer PP with pp_size > 1")
        if self.pipeline.schedule == "mpipe" and (self.accelerator.tp_size != 1 or self.accelerator.cp_size != 1
                                                  or self.accelerator.encoder_parallel.enabled):
            raise ValueError("MPipe VLM training requires TP1, CP1 and encoder_parallel disabled")
        if self.checkpoint.save_hf_weights and eager_pipeline:
            raise ValueError("HF export cannot gather eager pipeline stages. Use checkpoint.save_ckpt for DCP")

    def __post_init__(self) -> None:
hyper_parallel/trainer/runtime/pipeline.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class _TrainerStage(PipelineStage):
    """Preserve one auxiliary-loss context through each microbatch's backward."""

    def __init__(self, runtime: "TrainerPipeline", model: nn.Module) -> None:
        mesh = runtime.trainer.mesh
        partition = model._hp_pipeline_partition  # pylint: disable=protected-access
        super().__init__(
            model, partition.stage_index, partition.stage_count,
            device=runtime.trainer.device, group=mesh.pp_mesh.get_group(), mesh=mesh.pp_mesh, dyn_shape=True,
        )
        self.contexts = {}
        self.partition = partition
        self.runtime = runtime
        self.monitor = MoEMonitorCallback(model)

    def _forward_submodule(self, *args: torch.Tensor, **kwargs: dict) -> Any:
        """Run the local forward and capture stage-local metrics before the next microbatch."""
        runtime = self.runtime
        trainer = runtime.trainer
        inputs = {**kwargs["inputs"], "pipeline_inputs": args, "use_cache": False}
        loss_inputs = kwargs["loss_inputs"]
        counts = kwargs["counts"]
        micro_index = kwargs["micro_index"]
        prepare = getattr(trainer.loss_fn, "prepare_model_inputs", None)
        if callable(prepare) and self.partition.is_last:
            inputs = prepare(inputs, loss_inputs)
        context = trainer.model_fwd_context
        with context() if callable(context) else context:
            outputs = self.submodule(**inputs)
        router_losses = self.monitor.last_aux_losses()
        if router_losses:
            runtime.router_stats[micro_index, 0] += torch.stack(router_losses).detach().sum()
            runtime.router_stats[micro_index, 1] += len(router_losses)
        if not self.partition.is_last:
            return outputs
        loss, metrics = trainer.postforward(outputs, loss_inputs.get("labels"), current_token_counts=counts)
        runtime.metrics[micro_index] = {
            name: value.detach() for name, value in metrics.items() if name != "router_aux_loss"
        }
        return loss

    def forward_one_chunk(self, micro_index: int, args: Optional[tuple] = None,
                          kwargs: Optional[dict] = None) -> Any:
        """Fetch this DP replica's next batch and run the local stage forward.
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
            micro_index: Forward microbatch index within the optimizer step.
            args: Local positional inputs supplied by the schedule.
            kwargs: Unused schedule inputs. The Trainer supplies the batch fields.
        """
        runtime = self.runtime
        trainer = runtime.trainer
        inputs, loss_inputs, counts, scale = runtime.batch_for_chunk(self, micro_index)
        trainer.current_token_counts = counts
        callback = getattr(trainer, "channel_loss_callback", None)
        tracking = callback.micro_step_context(trainer.state, inputs) if callback is not None else nullcontext()
        with tracking:
            context = copy_context()
            scope = aux_loss_scale_context(scale)
            context.run(scope.__enter__)
            self.contexts[micro_index] = (context, scope)
            if callback is not None:
                inputs = inputs.copy()
                callback.strip_model_inputs(inputs)
            if self is runtime.stages[0]:
                trainer.model_integration.record_batch(inputs, loss_inputs)
            stage_kwargs = {"inputs": inputs, "loss_inputs": loss_inputs, "counts": counts, "micro_index": micro_index}
            result = context.run(super().forward_one_chunk, micro_index, args, stage_kwargs)
        prefetch_plan = getattr(trainer.train_dataloader, "prefetch_plan", None)
        if self is runtime.stages[-1] and callable(prefetch_plan):
            prefetch_plan()
        return result

    def backward_one_chunk(self, micro_index: int) -> None:
        """Run backward with the auxiliary-loss scale captured during forward.
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

        Args:
            micro_index: Index of the corresponding saved forward context.
        """
        context, scope = self.contexts.pop(micro_index)
        trainer = self.runtime.trainer
        try:
            if trainer.config.training.empty_cache_before_backward:
                empty_cache()
            with trainer.model_bwd_context:
                context.run(super().backward_one_chunk, micro_index)
            prefetch = getattr(trainer.train_dataloader, "prefetch", None)
            if self is self.runtime.stages[0] and callable(prefetch):
                prefetch()
        finally:
            context.run(scope.__exit__, None, None, None)

    def clear_cache(self) -> None:
        """Release microbatch contexts and saved activations after the schedule finishes."""
        for context, scope in self.contexts.values():
            context.run(scope.__exit__, None, None, None)
        self.contexts.clear()
        super().clear_cache()
        self.fwd_cache.clear()
        self.clear_states()
        self.last_stage_outputs = None


class TrainerPipeline:
    """Run a complete optimizer step's microbatches on one local stage.
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    """

    def __init__(self, trainer: Any) -> None:
        """Bind the local partition and its PP group to the Trainer."""
        self.trainer = trainer
        self.partition = trainer.model._hp_pipeline_partition  # pylint: disable=protected-access
        self.stages = [_TrainerStage(self, part) for part in getattr(trainer.model, "parts", (trainer.model,))]
        self.preprocess = None
        self.visual_inputs = {}
        if self.partition.mpipe:
            self.preprocess = trainer.model.build_mpipe_preprocess()
            # Frozen weights can differ after scratch init or checkpoint restore.
            group = trainer.mesh.pp_mesh.get_group()
            for tensor in (*self.preprocess.parameters(), *self.preprocess.buffers()):
                if not tensor.requires_grad:
                    local = tensor.to_local() if hasattr(tensor, "to_local") else tensor
                    dist.broadcast(local.detach(), group=group, group_src=0)
        self.batch_cache = {}
        self.schedule = None
        self.batches = None
        self.router_stats = None
        self.metrics = {}

    def batch_for_chunk(self, stage: PipelineStage, micro_index: int) -> tuple:
        """Share a microbatch and its token weight across this rank's virtual stages.
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
        Args:
            stage: Local chunk about to execute forward.
            micro_index: Microbatch index within the current optimizer step.
        """
        trainer = self.trainer
        if stage is self.stages[0]:
            inputs, loss_inputs = next(self.batches)
            inputs, loss_inputs = trainer.preforward(inputs), trainer.preforward(loss_inputs)
            counts = count_loss_token(loss_inputs)
            for name, value in counts.items():
                trainer.step_token_counts[name] = trainer.step_token_counts.get(name, 0) + value.detach()
            count = counts["foundation_tokens"]
            trainer.on_micro_step_begin({**inputs, **loss_inputs, "token_count": count})
            trainer.begin_fsdp_runtime_diagnostics(micro_index)
            mesh = trainer.mesh
            if mesh.sequence_parallel:
                group = mesh.device_mesh["tp"].get_group()
                count = count.clone()
                dist.all_reduce(count, group=group)
                count = count / dist.get_world_size(group)
            self.batch_cache[micro_index] = (inputs, loss_inputs, counts, count * mesh.dp_size * mesh.cp_size)
        if stage is self.stages[-1]:
            return self.batch_cache.pop(micro_index)
        return self.batch_cache[micro_index]

    def _load_visual_input(self, step, context):
        context.arg_mbs[step.micro_index] = self.visual_inputs.pop(step.micro_index)

    def _finish_step(self, losses: list, count: int) -> tuple[float, dict[str, float]]:
        """Publish per-microbatch callbacks and the same step numerators on every stage."""
        trainer = self.trainer
        group = trainer.mesh.pp_mesh.get_group()
        source = trainer.mesh.pp_mesh.rank_list[-1]
        keys = [tuple(self.metrics[i]) for i in range(count)] if self.partition.is_last else None
        metadata = [(keys, trainer.loss_names) if self.partition.is_last else None]
        dist.broadcast_object_list(metadata, src=source, group=group)
        keys, trainer.loss_names = metadata[0]
        columns = {name: i for i, name in enumerate(dict.fromkeys(name for row in keys for name in row), start=1)}
        values = torch.zeros((count, len(columns) + 1), device=trainer.device, dtype=torch.float32)
        if self.partition.is_last:
            values[:, 0] = torch.stack(losses).detach()
            for i, metrics in self.metrics.items():
                for name, value in metrics.items():
                    values[i, columns[name]] = value
        dist.broadcast(values, src=source, group=group)
        dist.all_reduce(self.router_stats, group=group)
        router_counts = self.router_stats[:, 1].tolist()
        totals = defaultdict(float)
        for i, names in enumerate(keys):
            metrics = {name: values[i, columns[name]] for name in names}
            if router_counts[i]:
                metrics["router_aux_loss"] = self.router_stats[i, 0] / router_counts[i]
            trainer.on_micro_step_end(metrics)
            for name, value in metrics.items():
                totals[name] += value.item()
        return sum(values[:, 0].tolist()), totals

    def run(self, batches: Iterator[tuple[dict, dict]], count: int) -> tuple[float, dict[str, float]]:
        """Consume batches in forward order and schedule their forward/backward work.
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        Args:
            batches: Stage-local iterator over Trainer model and loss inputs.
            count: Number of microbatches in this optimizer step.
        """
        if not count:
            raise ValueError("a pipeline optimizer step needs at least one microbatch")
        if self.schedule is None or self.schedule.micro_batch_num != count:
            if self.preprocess is not None:
                self.schedule = ScheduleMPipeTranspose(self.stages, count, self.preprocess, num_transpose_layers=1)
                self.schedule.register_custom_function(MetaStepType.DATA_LOAD, self._load_visual_input)
            else:
                schedule_type = {
                    "1f1b": Schedule1F1B, "gpipe": ScheduleGPipe, "interleaved_1f1b": ScheduleInterleaved1F1B,
                }[self.trainer.config.pipeline.schedule]
                self.schedule = schedule_type(self.stages, count)
        self.batches = iter(batches)
        self.router_stats = torch.zeros((count, 2), device=self.trainer.device, dtype=torch.float32)
        try:
            if self.preprocess is not None:
                prepared = []
                for index in range(count):
                    inputs, loss_inputs = next(self.batches)
                    inputs = inputs.copy()
                    if self.schedule.owner_of(index) == self.trainer.mesh.pp_rank:
                        self.visual_inputs[index] = self.preprocess.take_inputs(inputs)
                    prepared.append((inputs, loss_inputs))
                self.batches = iter(prepared)
            return self._finish_step(self.schedule.run(), count)
        finally:
            for stage in self.stages:
                stage.clear_cache()
            self.visual_inputs.clear()
            self.batch_cache.clear()
            self.batches = None
            self.router_stats = None
            self.metrics.clear()


__all__ = ["TrainerPipeline"]
hyper_parallel/trainer/text_trainer.py
305
306
307
308
309
310
311
312
313
314
        total_loss = 0.0
        total_loss_dict = defaultdict(int)

        if getattr(self.base.model, "_hp_pipeline_partition", None) is not None:
            batches = (self.base.get_batch(data_iterator) for _ in range(num_micro_steps))
            total_loss, total_loss_dict = self.base.pipeline_forward_backward(batches, num_micro_steps)
        else:
            for micro_step in range(num_micro_steps):
                self.base.model_reshard(micro_step, num_micro_steps)
                self.base.configure_fsdp_gradient_sync(