Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / callbacks / environ_meter_callback.py: 87%
258 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 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Training and environment metric collection callback."""
17from __future__ import annotations
19import time
20from collections.abc import Mapping, Sequence
21from typing import Any
23from hyper_parallel.trainer.runtime.distributed import get_world_size_safe
24from hyper_parallel.trainer.runtime.distributed import all_reduce
25from hyper_parallel.trainer.runtime.flops import estimate_step_flops
26from hyper_parallel.data.constants import IGNORE_INDEX
27from hyper_parallel.trainer.runtime.device import (
28 get_device_type,
29 get_torch_device,
30 is_device_runtime_simulated,
31)
33from .base import Callback, TrainerState
36class EnvironMeterCallback(Callback):
37 """Collect structured training, throughput, and memory metrics.
39 The callback is the single producer of ``trainer.step_train_metrics`` and
40 ``trainer.step_env_metrics``. Presentation and remote logging callbacks
41 consume those dictionaries without recalculating or reducing metrics.
42 """
44 def __init__(self, trainer: Any, *, microbatch_mean_metrics: Sequence[str] = ()) -> None:
45 """Initialize per-step and cumulative counters.
47 Args:
48 trainer: Trainer that owns the callback lifecycle.
49 microbatch_mean_metrics: Raw metric names to average over observed
50 micro-batches before the existing DP+CP mean reduction. Other
51 metrics retain the step values supplied by the Trainer.
52 """
53 super().__init__(trainer)
54 self._step_start_time = 0.0
55 self._local_step_tokens: Any = None
56 self._local_step_input_tokens: Any = None
57 self._local_step_seq_len_sq: Any = None
58 self._local_step_samples = 0
59 self._microbatch_mean_metrics = tuple(microbatch_mean_metrics)
60 self._local_mean_metrics: dict[str, tuple[Any, int]] = {}
61 self._consumed_tokens = 0
62 self._consumed_samples = 0
63 self.trainer.step_train_metrics = {}
64 self.trainer.step_env_metrics = {}
66 @staticmethod
67 def _scalar(value: Any, name: str) -> float:
68 """Convert a scalar or scalar tensor-like value to ``float``.
70 Args:
71 value: Scalar value to convert.
72 name: Metric name used in validation errors.
74 Returns:
75 Converted floating-point value.
77 Raises:
78 ValueError: If the value cannot be converted to a scalar float.
79 """
80 item = getattr(value, "item", None)
81 if callable(item):
82 value = item()
83 try:
84 return float(value)
85 except (TypeError, ValueError) as exc:
86 raise ValueError(f"Metric {name!r} must be scalar, but got {value!r}") from exc
88 @staticmethod
89 def _tensor_numel(value: Any) -> int | None:
90 """Return ``value.numel()`` when it exposes a tensor-like interface."""
91 numel = getattr(value, "numel", None)
92 if not callable(numel):
93 return None
94 return int(numel())
96 @classmethod
97 def _batch_tokens(cls, batch: Mapping[str, Any]) -> Any:
98 """Count text tokens without synchronizing a device scalar to the host."""
99 token_count = batch.get("token_count")
100 if token_count is not None:
101 return token_count
103 labels = batch.get("labels")
104 if labels is not None and callable(getattr(labels, "sum", None)):
105 return (labels != IGNORE_INDEX).sum()
107 attention_mask = batch.get("attention_mask")
108 attention_mask_shape = getattr(attention_mask, "shape", ())
109 if (
110 len(attention_mask_shape) <= 2
111 and attention_mask is not None
112 and callable(getattr(attention_mask, "sum", None))
113 ):
114 return attention_mask.sum()
116 input_ids = batch.get("input_ids")
117 input_numel = cls._tensor_numel(input_ids)
118 if input_numel is not None:
119 return input_numel
120 return 0
122 @classmethod
123 def _batch_input_geometry(cls, batch: Mapping[str, Any]) -> tuple[Any, Any] | None:
124 """Return model-input tokens and the sum of squared sequence lengths.
126 The loss token count drops masked prompt tokens, but the model still
127 runs attention and the FFN over them, so FLOPs need their own count:
128 the tokens that reach attention plus ``sum(S ** 2)`` over the real
129 attention boundaries.
131 Every returned quantity is local to this rank, because
132 :meth:`on_step_end` reduces them over DP+CP itself.
134 Args:
135 batch: One micro-batch mapping.
137 Returns:
138 ``(input_tokens, sum_seq_len_sq)`` for the sequences that reach
139 attention, or ``None`` when the batch exposes no input geometry.
140 """
141 cu_seq_lens = batch.get("cu_seq_lens")
142 if cu_seq_lens is not None and callable(getattr(cu_seq_lens, "diff", None)):
143 local_tokens = cls._tensor_numel(batch.get("input_ids"))
144 lengths = cu_seq_lens.diff()
145 covered = int(lengths.sum())
146 # Packed boundaries are only usable when they describe the tokens
147 # this rank actually holds. Under context parallelism the packed
148 # boundaries may still span the global sequence, and then the local
149 # ``input_ids`` fallbacks below are the honest answer.
150 if covered > 0 and (local_tokens is None or covered == local_tokens):
151 return lengths.sum(), (lengths * lengths).sum()
153 attention_mask = batch.get("attention_mask")
154 if (
155 attention_mask is not None
156 and len(getattr(attention_mask, "shape", ())) == 2
157 and callable(getattr(attention_mask, "sum", None))
158 ):
159 lengths = attention_mask.sum(dim=-1)
160 return lengths.sum(), (lengths * lengths).sum()
162 shape = getattr(batch.get("input_ids"), "shape", None)
163 if shape is None or len(shape) < 2:
164 return None
165 rows = int(shape[0])
166 seq_length = int(shape[-1])
167 if rows <= 0 or seq_length <= 0:
168 return None
169 return rows * seq_length, rows * seq_length * seq_length
171 @staticmethod
172 def _batch_samples(batch: Mapping[str, Any]) -> int:
173 """Count logical samples in one micro-batch."""
174 value = batch.get("input_ids")
175 if value is None:
176 value = batch.get("labels")
177 shape = getattr(value, "shape", None)
178 if shape is None or len(shape) == 0:
179 return 0
180 if len(shape) == 1:
181 return 1
182 return int(shape[0])
184 @staticmethod
185 def _batch_mapping(value: Any) -> Mapping[str, Any] | None:
186 """Return metric inputs for a mapping or prepared runtime batch."""
187 if isinstance(value, Mapping):
188 return value
189 loss_count_inputs = getattr(value, "loss_count_inputs", None)
190 if not callable(loss_count_inputs):
191 return None
192 metric_inputs = loss_count_inputs()
193 return metric_inputs if isinstance(metric_inputs, Mapping) else None
195 @classmethod
196 def _micro_batches(cls, value: Any) -> list[Mapping[str, Any]]:
197 """Normalize callback input into a list of mapping micro-batches."""
198 if value is None:
199 return []
200 batch = cls._batch_mapping(value)
201 if batch is not None:
202 return [batch]
203 if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
204 batches = []
205 for item in value:
206 batch = cls._batch_mapping(item)
207 if batch is not None:
208 batches.append(batch)
209 return batches
210 return []
212 def _metric_group(self) -> Any:
213 """Return the DP+CP process group used by loss normalization."""
214 dp_cp_mesh = getattr(self.trainer.mesh, "dp_cp_mesh", None)
215 if dp_cp_mesh is None:
216 return None
217 return dp_cp_mesh.get_group()
219 def _reduce(self, value: Any, op: str) -> float:
220 """Reduce one scalar metric, with a single-process no-op fallback."""
221 if get_world_size_safe() <= 1:
222 return float(value)
223 reduced = all_reduce(value, op=op, group=self._metric_group())
224 return float(reduced)
226 def _pipeline_max(self, value: float) -> float:
227 """Extend a DP+CP maximum across physical pipeline stages."""
228 mesh = getattr(self.trainer, "mesh", None)
229 pp_mesh = getattr(mesh, "pp_mesh", None)
230 if get_world_size_safe() <= 1 or int(getattr(mesh, "pp_size", 1)) <= 1 or pp_mesh is None:
231 return float(value)
232 return float(all_reduce(value, op="max", group=pp_mesh.get_group()))
234 @staticmethod
235 def _accumulate_scalar(current: Any, value: Any) -> Any:
236 """Add one batch scalar to a running per-step total.
238 Args:
239 current: Running total, or ``None`` before the first batch.
240 value: Batch value to add; may be a device scalar.
242 Returns:
243 Updated running total that never aliases the batch tensor.
244 """
245 detached = value.detach() if callable(getattr(value, "detach", None)) else value
246 if current is None:
247 return detached.clone() if callable(getattr(detached, "clone", None)) else detached
248 return current + detached
250 def _accumulate_batches(self, value: Any) -> None:
251 """Accumulate batch metrics without retaining input tensor references."""
252 for batch in self._micro_batches(value):
253 self._local_step_tokens = self._accumulate_scalar(
254 self._local_step_tokens, self._batch_tokens(batch)
255 )
256 geometry = self._batch_input_geometry(batch)
257 if geometry is not None:
258 input_tokens, seq_len_sq = geometry
259 self._local_step_input_tokens = self._accumulate_scalar(
260 self._local_step_input_tokens, input_tokens
261 )
262 self._local_step_seq_len_sq = self._accumulate_scalar(
263 self._local_step_seq_len_sq, seq_len_sq
264 )
265 self._local_step_samples += self._batch_samples(batch)
267 def _cp_size(self) -> int:
268 """Return the validated context-parallel size of the trainer mesh."""
269 cp_size = int(getattr(self.trainer.mesh, "cp_size", 1))
270 if cp_size < 1:
271 raise ValueError(f"mesh.cp_size must be positive, but got {cp_size}")
272 return cp_size
274 def _global_samples(self) -> int:
275 """Reduce samples across DP+CP while removing CP replicas."""
276 cp_size = self._cp_size()
277 reduced_samples = self._reduce(self._local_step_samples, op="sum")
278 global_samples = reduced_samples / cp_size
279 if not global_samples.is_integer():
280 raise ValueError(
281 "Reduced sample count must be divisible by cp_size, "
282 f"but got reduced_samples={reduced_samples} and cp_size={cp_size}"
283 )
284 return int(global_samples)
286 def _current_lr(self) -> float:
287 """Return the maximum learning rate across scheduler or optimizer groups."""
288 schedulers = self.trainer.lr_scheduler
289 if schedulers is not None:
290 scheduler_list = schedulers if isinstance(schedulers, list) else [schedulers]
291 learning_rates = []
292 for scheduler in scheduler_list:
293 for learning_rate in scheduler.get_last_lr():
294 learning_rates.append(float(learning_rate))
295 if learning_rates:
296 return max(learning_rates)
298 optimizers = self.trainer.optimizer
299 optimizer_list = optimizers if isinstance(optimizers, list) else [optimizers]
300 learning_rates = []
301 for optimizer in optimizer_list:
302 if optimizer is None:
303 continue
304 for param_group in optimizer.param_groups:
305 learning_rates.append(float(param_group["lr"]))
306 return max(learning_rates, default=0.0)
308 def _memory_metrics(self) -> dict[str, float]:
309 """Collect maximum accelerator memory metrics, if available."""
310 if get_device_type() == "cpu" or is_device_runtime_simulated():
311 # Logical simulation never touches the accelerator runtime;
312 # querying allocator statistics would initialize it.
313 return {}
314 device = get_torch_device()
315 allocated = self._pipeline_max(self._reduce(device.max_memory_allocated(), op="max"))
316 reserved = self._pipeline_max(self._reduce(device.max_memory_reserved(), op="max"))
317 gibibyte = 1024 ** 3
318 return {
319 "memory/device_max_allocated_gb": allocated / gibibyte,
320 "memory/device_max_reserved_gb": reserved / gibibyte,
321 }
323 def state_dict(self) -> dict[str, int]:
324 """Return cumulative data metrics saved alongside training progress."""
325 return {
326 "consumed_tokens": self._consumed_tokens,
327 "consumed_samples": self._consumed_samples,
328 }
330 def load_state_dict(self, state_dict: dict[str, int]) -> None:
331 """Restore cumulative metric state.
333 Args:
334 state_dict: Mapping produced by :meth:`state_dict`.
336 Raises:
337 ValueError: If required counters are missing or negative.
338 """
339 try:
340 consumed_tokens = int(state_dict["consumed_tokens"])
341 consumed_samples = int(state_dict["consumed_samples"])
342 except (KeyError, TypeError, ValueError) as exc:
343 raise ValueError(
344 "EnvironMeterCallback state must contain integer consumed_tokens and consumed_samples"
345 ) from exc
346 if consumed_tokens < 0 or consumed_samples < 0:
347 raise ValueError("EnvironMeterCallback cumulative counters must be non-negative")
348 self._consumed_tokens = consumed_tokens
349 self._consumed_samples = consumed_samples
351 def on_step_begin(
352 self,
353 state: TrainerState,
354 micro_batches: list[dict[str, Any]] | None = None,
355 **kwargs: Any,
356 ) -> None:
357 """Start timing and count local input tokens and samples.
359 Args:
360 state: Current training progress.
361 micro_batches: Batches available before the step starts.
362 **kwargs: Unused callback context.
363 """
364 del state, kwargs
365 self._local_step_tokens = None
366 self._local_step_input_tokens = None
367 self._local_step_seq_len_sq = None
368 self._local_step_samples = 0
369 self._step_start_time = time.perf_counter()
370 self._local_mean_metrics.clear()
371 self._accumulate_batches(micro_batches)
373 def on_micro_step_begin(
374 self,
375 state: TrainerState,
376 micro_batch: dict[str, Any],
377 **kwargs: Any,
378 ) -> None:
379 """Accumulate metrics for one prepared micro-batch.
381 Args:
382 state: Current training progress.
383 micro_batch: Prepared inputs and lightweight metric metadata.
384 **kwargs: Unused callback context.
385 """
386 del state, kwargs
387 self._accumulate_batches(micro_batch)
389 def on_micro_step_end(self, state: TrainerState, loss_dict: dict[str, Any], **kwargs: Any) -> None:
390 """Accumulate explicitly registered micro-batch means without host reads."""
391 del state, kwargs
392 for name in self._microbatch_mean_metrics:
393 value = loss_dict.get(name)
394 if value is not None:
395 total, count = self._local_mean_metrics.get(name, (None, 0))
396 self._local_mean_metrics[name] = (self._accumulate_scalar(total, value), count + 1)
398 def _synchronize_pipeline_step(self) -> None:
399 """Wait for asynchronous work only when eager PP requires aligned timing."""
400 mesh = getattr(self.trainer, "mesh", None)
401 pp_active = int(getattr(mesh, "pp_size", 1)) > 1 and getattr(mesh, "pp_mesh", None) is not None
402 if get_device_type() == "cpu" or not pp_active:
403 return
404 synchronize = getattr(get_torch_device(), "synchronize", None)
405 if callable(synchronize):
406 synchronize()
408 def on_step_end(
409 self,
410 state: TrainerState,
411 loss: float,
412 loss_dict: dict[str, float] | None,
413 grad_norm: float,
414 **kwargs: Any,
415 ) -> None:
416 """Reduce and publish metrics for one completed optimizer step.
418 Args:
419 state: Current training progress.
420 loss: Aggregated loss for the optimizer step.
421 loss_dict: Named loss values for the optimizer step.
422 grad_norm: Gradient norm measured before the optimizer update.
423 **kwargs: Unused callback context.
424 """
425 del state, kwargs
426 self._synchronize_pipeline_step()
427 step_time = max(time.perf_counter() - self._step_start_time, 0.0)
428 global_step_time = self._pipeline_max(self._reduce(step_time, op="max"))
429 local_step_tokens = 0 if self._local_step_tokens is None else self._local_step_tokens
430 global_tokens = int(self._reduce(local_step_tokens, op="sum"))
431 global_samples = self._global_samples()
432 cp_size = self._cp_size()
433 local_input_tokens = (
434 0 if self._local_step_input_tokens is None else self._local_step_input_tokens
435 )
436 local_seq_len_sq = (
437 0 if self._local_step_seq_len_sq is None else self._local_step_seq_len_sq
438 )
439 # Context parallelism slices a sequence along its length, so each rank
440 # only sees ``(S / cp) ** 2`` while the real attention cost is ``S ** 2``.
441 # Summing over DP+CP therefore needs one factor of ``cp_size`` to
442 # restore the per-sequence square. Input tokens need no correction
443 # because the slices add back up to ``S``.
444 global_input_tokens = self._reduce(local_input_tokens, op="sum")
445 global_seq_len_sq = self._reduce(local_seq_len_sq, op="sum") * cp_size
446 self._local_step_tokens = None
447 self._local_step_input_tokens = None
448 self._local_step_seq_len_sq = None
449 self._local_step_samples = 0
450 self._consumed_tokens += global_tokens
451 self._consumed_samples += global_samples
453 train_metrics = {
454 "training/total_loss": self._reduce(self._scalar(loss, "total_loss"), op="mean"),
455 "training/grad_norm": self._reduce(self._scalar(grad_norm, "grad_norm"), op="mean"),
456 "training/lr": self._current_lr(),
457 }
458 for name, value in sorted((loss_dict or {}).items()):
459 if name in self._local_mean_metrics:
460 total, count = self._local_mean_metrics[name]
461 value = total / count
462 metric_name = name if name.startswith("training/") else f"training/{name}"
463 train_metrics[metric_name] = self._reduce(self._scalar(value, name), op="mean")
464 self._local_mean_metrics.clear()
466 tokens_per_second = global_tokens / global_step_time if global_step_time > 0 else 0.0
467 env_metrics = {
468 **train_metrics,
469 "performance/step_time": global_step_time,
470 "performance/tokens_per_second": tokens_per_second,
471 "data/step_tokens": float(global_tokens),
472 "data/consumed_tokens": float(self._consumed_tokens),
473 "data/step_samples": float(global_samples),
474 "data/consumed_samples": float(self._consumed_samples),
475 **self._memory_metrics(),
476 }
478 training_config = getattr(getattr(self.trainer, "config", None), "training", None)
479 model_config = getattr(self.trainer, "model_config", None)
480 if (
481 getattr(training_config, "log_tflops", False)
482 and model_config is not None
483 and global_input_tokens > 0
484 and global_step_time > 0
485 ):
486 step_flops = estimate_step_flops(
487 model_config, global_input_tokens, global_seq_len_sq
488 )
489 if step_flops is not None:
490 env_metrics["performance/tflops_per_device"] = (
491 step_flops / (global_step_time * get_world_size_safe()) / 1e12
492 )
494 self.trainer.step_train_metrics = train_metrics
495 self.trainer.step_env_metrics = env_metrics