Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / config_adapter / _search_runner.py: 96%
244 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"""Search runner -- bridges NormalizedConfig to the ND search engine.
17Hands a :class:`NormalizedConfig` to the ND search as the mapping
18``Parallelize`` parses directly, post-filters by user candidate lists and
19memory budget, and returns the optimal strategy.
20"""
22import copy
23import logging
24from typing import Any, Dict, FrozenSet, List, Mapping, Optional, Set, Tuple, TYPE_CHECKING
26from hyper_parallel.auto_parallel._hf_model_spec import EXEC_OVERRIDE_KEYS
27from hyper_parallel.auto_parallel._model_spec import ModelSpec, model_fields
28from hyper_parallel.auto_parallel.config_adapter._normalized_config import NormalizedConfig
31if TYPE_CHECKING:
32 import hyper_parallel.auto_parallel.sapp_nd.nd.parallelize as Par
33 import hyper_parallel.auto_parallel.sapp_nd.nd.dimensions as Dim
34 import hyper_parallel.auto_parallel.sapp_nd.nd.common.hardware as Hard
36logger = logging.getLogger(__name__)
38# A generic census does not specify the module regions the trainer's
39# selective mode now requires, so it cannot add that mode to an auto search.
40TRAINER_RECOMPUTE_MODES = ("off", "full")
41# The search config's recompute values that choose among those modes: "auto"
42# one for every layer, "per_layer" one for each layer, which the trainer runs
43# as activation_checkpoint.layers.
44CHOSEN_RECOMPUTE = ("auto", "per_layer")
47def _get_dim_module():
48 """Lazy-import the sapp_nd dimensions module."""
49 import hyper_parallel.auto_parallel.sapp_nd.nd.dimensions as dim_mod # pylint: disable=C0415
50 return dim_mod
53def _get_machine_mod():
54 """Lazy-import the sapp_nd hardware module."""
55 import hyper_parallel.auto_parallel.sapp_nd.nd.common.hardware as hw_mod # pylint: disable=C0415
56 return hw_mod
59def _search_dim_map():
60 """Return the mapping of NormalizedConfig keys to sapp_nd Dimension objects.
62 Lazily loaded to avoid importing sapp_nd at module-import time.
63 """
64 dim_mod = _get_dim_module()
65 return {
66 "data_parallel_replicate_degree": dim_mod.DP,
67 "tensor_parallel_degree": dim_mod.TP,
68 "pipeline_parallel_degree": dim_mod.PP,
69 "context_parallel_degree": dim_mod.CP,
70 "expert_parallel_degree": dim_mod.EP,
71 "micro_batch_num": dim_mod.MBN,
72 # OP carries the FSDP/optimizer shard degree (ccfg.os_max_shard),
73 # so mapping it here is what lets ND search that dimension.
74 "data_parallel_shard_degree": dim_mod.OP,
75 }
78def _validate_before_search(config: NormalizedConfig) -> None:
79 """Check required model fields are populated (>0) before search.
81 Raises:
82 ValueError: If any required field is missing or zero.
83 """
84 model = config.model_spec
85 required = {
86 "model_spec.num_hidden_layers": model.get("num_hidden_layers", 0),
87 "model_spec.hidden_size": model.get("hidden_size", 0),
88 "model_spec.num_attention_heads": model.get("num_attention_heads", 0),
89 "model_spec.vocab_size": model.get("vocab_size", 0),
90 "cluster_spec": config.cluster_spec,
91 }
92 missing = []
93 for name, value in required.items():
94 if name == "cluster_spec":
95 if not isinstance(value, dict) or not value:
96 missing.append(name)
97 elif value <= 0:
98 missing.append(name)
99 if missing:
100 raise ValueError(
101 "Required fields missing or zero before ND search: "
102 f"{', '.join(missing)}"
103 )
106def _build_model_dict(model: Dict[str, Any]) -> Dict[str, Any]:
107 """Build the ``model`` section of the HP YAML from *model* spec.
109 The model's fields go through the model spec, whose names are the HP
110 YAML's, and the run keys the parser reads from ``config_overrides``
111 pass through as they are. The adapter's own keys, such as the
112 micro-batch size, reach the HP YAML through their own sections.
114 Args:
115 model: The ``model_spec`` dict from :class:`NormalizedConfig`.
117 Returns:
118 A dict suitable for the ``model`` key of a HP ``train.yaml``.
119 """
120 spec = ModelSpec.from_dict(model_fields(model))
121 overrides = spec.to_dict()
122 overrides.pop("name", None)
123 overrides.update({key: model[key] for key in EXEC_OVERRIDE_KEYS if key in model})
124 return {"name": spec.name, "config_overrides": overrides}
127# The strategy, under every name the cost model reads it by, in the sections
128# a train.yaml states its run in: the search sets it, from its candidates or
129# its own config, so the train.yaml's values give way. The rest of each
130# section is the run's.
131_STRATEGY_KEYS: Dict[str, FrozenSet[str]] = {
132 "accelerator": frozenset({
133 "dp_replicate", "dp_shard", "tp_size", "tp_degree", "pp_size", "pipeline_parallel_degree",
134 "cp_size", "context_parallel_degree", "ep_size", "expert_parallel_degree",
135 "expert_tensor_parallel_degree", "micro_batch_num", "optimizer_weight_shard_size",
136 "pipeline_scheduler", "pp_interleave_num",
137 }),
138 "fsdp_config": frozenset({"dp_shard_size"}),
139 "training": frozenset({"global_batch_size", "micro_batch_size", "micro_batch_num"}),
140}
143def _stated_run(config: NormalizedConfig) -> Dict[str, Any]:
144 """Return the run the train.yaml states, less the strategy the search sets.
146 Args:
147 config: The normalized config whose ``run`` the train.yaml filled.
149 Returns:
150 A copy of ``config.run``, its sections without the strategy's keys.
151 """
152 run = copy.deepcopy(config.run)
153 for section, strategy in _STRATEGY_KEYS.items():
154 stated = run.get(section)
155 if isinstance(stated, dict):
156 run[section] = {key: value for key, value in stated.items() if key not in strategy}
157 return run
160def _memory_budget_gb(config: NormalizedConfig) -> float:
161 """Return the per-device memory budget in GB, or ``0.0`` if unconstrained.
163 ``constraint.memory_limit_gb`` is the budget the user asked for and
164 ``cluster_spec.device_memory_gb`` the hardware ceiling, so the search
165 must respect whichever of the two is tighter.
167 Args:
168 config: The normalized config carrying constraint and cluster spec.
170 Returns:
171 The tighter positive budget in GB, or ``0.0`` when neither is set.
172 """
173 limit = float(config.constraint.get("memory_limit_gb", 0.0) or 0.0)
174 device = float(config.cluster_spec.get("device_memory_gb", 0.0) or 0.0)
175 budgets = [value for value in (limit, device) if value > 0]
176 return min(budgets) if budgets else 0.0
179def _pinned_or_first(config: NormalizedConfig, constraint_key: str, space_key: str,
180 default: List[Any]) -> Any:
181 """Return the degree *constraint_key* pins, else the first candidate.
183 Args:
184 config: The normalized config carrying constraint and search space.
185 constraint_key: The ``constraint`` entry that pins the degree.
186 space_key: The ``search_space`` entry listing its candidates.
187 default: The candidates when the search space lists none.
189 Returns:
190 The pinned degree when it is positive, else the first candidate,
191 a placeholder the search replaces.
192 """
193 pinned = config.constraint.get(constraint_key)
194 if pinned is not None and pinned > 0:
195 return pinned
196 return config.search_space.get(space_key, default)[0]
199def _build_strategy_dicts(
200 config: NormalizedConfig, run: Dict[str, Any],
201) -> Tuple[Dict[str, Any], Dict[str, Any]]:
202 """Build the ``accelerator`` and ``fsdp_config`` sections of the HP YAML.
204 The strategy goes over the sections the train.yaml states, which this
205 takes out of *run*.
206 """
207 accel: Dict[str, Any] = dict(run.pop("accelerator", None) or {})
208 fsdp: Dict[str, Any] = dict(run.pop("fsdp_config", None) or {})
210 # Fixed dimensions -- write actual value.
211 fixed_map = {
212 "fixed_dp_degree": ("dp_replicate", "data_parallel_replicate_degree", [1]),
213 "fixed_tp_degree": ("tp_size", "tensor_parallel_degree", [1]),
214 "fixed_pp_degree": ("pp_size", "pipeline_parallel_degree", [1]),
215 "fixed_cp_degree": ("cp_size", "context_parallel_degree", [1]),
216 "fixed_ep_degree": ("ep_size", "expert_parallel_degree", [1]),
217 "fixed_etp_degree": ("expert_tensor_parallel_degree", "expert_tensor_parallel_degree", [0]),
218 }
219 for constraint_key, (accel_key, space_key, default) in fixed_map.items():
220 accel[accel_key] = _pinned_or_first(config, constraint_key, space_key, default)
222 # micro_batch_num has no accelerator entry of its own, so a fixed value
223 # would be dropped and the global-batch-size check would then reject the
224 # only config the user asked for.
225 accel["micro_batch_num"] = int(
226 _pinned_or_first(config, "fixed_micro_batch_num", "micro_batch_num", [1])
227 )
228 fsdp["dp_shard_size"] = int(
229 _pinned_or_first(config, "fixed_fsdp_degree", "data_parallel_shard_degree", [1])
230 )
232 # CP algorithm: propagate to yaml so CostModelParserHyperV2 can read it.
233 cp_algo = config.estimator.get("cp_algo")
234 if cp_algo:
235 accel["context_parallel_algo"] = cp_algo
237 # Optional accelerator fields that affect memory estimation.
238 owss = config.model_spec.get("optimizer_weight_shard_size")
239 if owss and owss > 0:
240 accel["optimizer_weight_shard_size"] = owss
242 use_sp = config.model_spec.get("use_seq_parallel", True)
243 accel.setdefault("sequence_parallel", bool(use_sp))
244 return accel, fsdp
247def _build_hp_yaml_dict(config: NormalizedConfig) -> dict:
248 """Build an AutoModels-shaped cost-model YAML dict from *config*.
250 Fixed dimensions (``constraint.fixed_*_degree``) are written directly
251 into the strategy sections. Dimensions with search-space candidates
252 use the first candidate as a placeholder -- the actual search is driven
253 by the ``dimensions`` parameter passed to :class:`Parallelize`. The
254 strategy goes over the run the train.yaml states, which stays as stated.
255 """
256 model = config.model_spec
257 constraint = config.constraint
258 run = _stated_run(config)
259 accel, fsdp = _build_strategy_dicts(config, run)
261 recompute = config.estimator.get("recompute_strategy", "none")
263 cluster = config.cluster_spec
264 # The train.yaml's pricing options, beneath the search's own device count
265 # and memory budget.
266 context: Dict[str, Any] = dict(run.pop("context", None) or {})
267 # ND prunes the space against ccfg.device_capacity, which the parser reads
268 # from this field, so the user's memory_limit_gb has to reach it here.
269 budget_gb = _memory_budget_gb(config)
270 if budget_gb > 0:
271 context["max_device_memory"] = f"{budget_gb}GB"
272 device_num = cluster.get("num_nodes", 0) * cluster.get("cards_per_node", 0)
273 if device_num > 0:
274 context["device_num"] = int(device_num)
275 visual_seq_len = model.get("visual_seq_len")
276 if visual_seq_len:
277 context["visual_seq_len"] = int(visual_seq_len)
279 # Choosing the recompute, the search keeps what fits fully recomputed:
280 # describe it so.
281 stated_mode = "full" if recompute in CHOSEN_RECOMPUTE else {"none": "off"}.get(recompute, recompute)
282 gc_dict: Dict[str, Any] = {"mode": stated_mode}
283 recompute_slice = model.get("recompute_slice_activation")
284 if recompute_slice is not None:
285 gc_dict["recompute_slice_activation"] = bool(recompute_slice)
287 model_dict = _build_model_dict(model)
289 hp_yaml: dict = {
290 **run,
291 "model": {**run.get("model", {}), **model_dict},
292 "training": {
293 **run.get("training", {}),
294 "global_batch_size": constraint.get("global_batch_size", 0),
295 "micro_batch_size": model.get("local_batch_size", 1),
296 "micro_batch_num": accel.pop("micro_batch_num", 1),
297 },
298 "accelerator": accel,
299 "fsdp_config": fsdp,
300 "activation_checkpoint": gc_dict,
301 "dataset": {
302 "data_transform": {
303 "max_seq_len": model.get("max_position_embeddings", 4096),
304 },
305 },
306 }
308 if context:
309 hp_yaml["context"] = context
311 return hp_yaml
315# The names a search config may give its devices, and the sapp_nd device
316# codes they mean: the Ascend 910B is the Atlas A2 series' chip, and the
317# 910C, CANN's ascend910_93, the A3's. A generic "ascend" stays A2.
318_DEVICE_CODES: Dict[str, str] = {
319 "a2": "A2", "a3": "A3", "v100": "V100",
320 "ascend": "A2", "ascend910": "A2", "ascend910b": "A2",
321 "ascend910c": "A3", "ascend910_93": "A3",
322}
325def _build_machine(config: NormalizedConfig) -> Any:
326 """Build a ``Hard.Machine`` from cluster_spec."""
327 hw_mod = _get_machine_mod()
328 cluster = config.cluster_spec
329 nodes = max(1, cluster.get("num_nodes", 1))
330 cards_per_node = max(1, cluster.get("cards_per_node", 8))
331 total_devices = nodes * cards_per_node
332 device_type = str(cluster.get("device_type", "A2"))
333 return hw_mod.Machine(total_devices, _DEVICE_CODES.get(device_type.lower(), device_type))
336def _resolve_search_dimensions(config: NormalizedConfig) -> Tuple[List[Any], Set[Any]]:
337 """Return search dimensions and the set of dimensions with user candidates.
339 List-valued entries in ``config.search_space`` are treated as
340 **output** (search) dimensions. Entries absent from
341 ``config.search_space`` (``"auto"`` in YAML) are also included -- they
342 will be determined by ND's ``bound_space()``.
344 Returns:
345 A tuple ``(dims, candidate_dims)`` where *dims* is the list of
346 ``Dim`` objects to pass to ND and *candidate_dims* is the set of
347 Dim objects for which the user supplied an explicit candidate list
348 (used by :func:`_post_filter`).
349 """
350 dims: List[Any] = []
351 candidate_dims: Set[Any] = set()
352 space = config.search_space
353 for space_key, dim_obj in _search_dim_map().items():
354 candidates = space.get(space_key)
355 if candidates is not None and len(candidates) > 1:
356 dims.append(dim_obj)
357 candidate_dims.add(dim_obj)
358 elif space_key not in space:
359 dims.append(dim_obj)
360 return dims, candidate_dims
363def _filter_by_memory(scored_space: list, budget_gb: float) -> list:
364 """Drop entries whose peak-memory estimate exceeds *budget_gb*.
366 ND already prunes against the device capacity while it generates the
367 space; this is the gate that holds when a strategy is scored under a
368 capacity looser than the budget the caller asked for.
370 Args:
371 scored_space: Scored entries ``(strategy, memory_mb, score, ...)``.
372 budget_gb: Per-device budget in GB; ``0`` disables the gate.
374 Returns:
375 The entries that fit. May be empty, which means the budget rules
376 out every strategy the search found.
377 """
378 if budget_gb <= 0:
379 return list(scored_space)
380 budget_mb = budget_gb * 1024.0
381 kept = [entry for entry in scored_space if float(entry[1]) <= budget_mb]
382 if len(kept) < len(scored_space):
383 logger.info(
384 "Memory filter dropped %d of %d strategies above %.1f GB.",
385 len(scored_space) - len(kept),
386 len(scored_space),
387 budget_gb,
388 )
389 return kept
392def _post_filter(
393 scored_space: list,
394 config: NormalizedConfig,
395 candidate_dims: Optional[Set[Any]] = None,
396) -> list:
397 """Keep only entries whose dimension values are in the user's candidate lists.
399 Args:
400 scored_space: The scored strategy list from ND engine.
401 config: The normalized config containing ``search_space``.
402 candidate_dims: The set of Dim objects that have user-supplied
403 candidate lists with more than one value. If *None*, the
404 set is derived from *config* (backward-compatible).
406 Returns:
407 The entries that fit the memory budget and sit in every list. Empty
408 when none does: a strategy outside the lists is never returned in
409 their place, and the caller refuses the search.
410 """
411 space = config.search_space
412 if candidate_dims is None:
413 candidate_dims = set()
414 for space_key, dim_obj in _search_dim_map().items():
415 candidates = space.get(space_key)
416 if candidates is not None and len(candidates) > 1:
417 candidate_dims.add(dim_obj)
419 candidate_map: Dict[Any, List[int]] = {}
420 for space_key, dim_obj in _search_dim_map().items():
421 if dim_obj not in candidate_dims:
422 continue
423 candidates = space.get(space_key)
424 if candidates is not None:
425 candidate_map[dim_obj] = candidates
427 feasible = _filter_by_memory(scored_space, _memory_budget_gb(config))
429 filtered = []
430 for entry in feasible:
431 dims_val = entry[0].dims_val # type: ignore[index]
432 keep = True
433 for dim_obj, allowed in candidate_map.items():
434 actual = dims_val.get(dim_obj)
435 if actual is not None and actual not in allowed:
436 keep = False
437 break
438 if keep:
439 filtered.append(entry)
440 return filtered
443def _no_candidate_match(feasible: list, config: NormalizedConfig, candidate_dims: Set[Any]) -> str:
444 """Say why no strategy that fits the budget is in the candidate lists.
446 ND searches each dimension within its own bounds and the lists only
447 filter what it found, so a list can ask for degrees the search never
448 reached. Naming the degrees it did reach shows which.
450 Args:
451 feasible: The scored entries that fit the memory budget.
452 config: The normalized config whose ``search_space`` holds the lists.
453 candidate_dims: The dimensions that have a list of their own.
455 Returns:
456 The refusal, naming each list no fitting strategy meets.
457 """
458 unmet = []
459 for space_key, dim_obj in _search_dim_map().items():
460 if dim_obj not in candidate_dims:
461 continue
462 asked = list(config.search_space.get(space_key, []))
463 found = sorted({entry[0].dims_val.get(dim_obj) for entry in feasible} - {None})
464 if not set(found) & set(asked):
465 unmet.append(f"{space_key} asks {asked}, the strategies that fit take {found}")
466 why = "; ".join(unmet) if unmet else "each list is met by some of them, but never all at once"
467 return (
468 f"None of the {len(feasible)} strategies that fit the memory budget is in the candidate "
469 f"lists: {why}. ND searches each dimension within its own bounds and the lists only "
470 "filter what it finds: widen the lists, or the budget."
471 )
474def _pinned_degree(config: NormalizedConfig, constraint_key: str, space_key: str) -> int:
475 """Return the degree of a dimension the search did not vary.
477 Args:
478 config: The normalized config carrying constraint and search space.
479 constraint_key: The ``constraint`` entry that pins the degree.
480 space_key: The ``search_space`` entry listing its candidates.
482 Returns:
483 The pinned degree, else the only candidate, else 1.
484 """
485 pinned = config.constraint.get(constraint_key)
486 if not pinned:
487 candidates = config.search_space.get(space_key) or []
488 pinned = candidates[0] if len(candidates) == 1 else 1
489 return int(pinned)
492def _format_result(best_entry: tuple, config: NormalizedConfig) -> Dict[str, Any]:
493 """Convert the best ND result entry into a flat result dict."""
494 dim_mod = _get_dim_module()
495 dims_val = best_entry[0].dims_val # type: ignore[index]
496 dim_to_key = {
497 dim_mod.DP: "dp",
498 dim_mod.TP: "tp",
499 dim_mod.PP: "pp",
500 dim_mod.CP: "cp",
501 dim_mod.EP: "ep",
502 dim_mod.MBN: "micro_batch_num",
503 dim_mod.OP: "dp_shard",
504 }
505 result: Dict[str, Any] = {
506 "memory_estimate_mb": float(best_entry[1]),
507 "score": float(best_entry[2]),
508 }
509 for dim_obj, key in dim_to_key.items():
510 if dim_obj in dims_val:
511 result[key] = int(dims_val[dim_obj])
512 # A pinned dimension is absent from dims_val, so fill it from what pinned
513 # it: the searcher never varied it, but every consumer still reads it.
514 fixed_from = {
515 "dp": ("fixed_dp_degree", "data_parallel_replicate_degree"),
516 "tp": ("fixed_tp_degree", "tensor_parallel_degree"),
517 "pp": ("fixed_pp_degree", "pipeline_parallel_degree"),
518 "cp": ("fixed_cp_degree", "context_parallel_degree"),
519 "ep": ("fixed_ep_degree", "expert_parallel_degree"),
520 "micro_batch_num": ("fixed_micro_batch_num", "micro_batch_num"),
521 }
522 for key, (constraint_key, space_key) in fixed_from.items():
523 if key not in result:
524 result[key] = _pinned_degree(config, constraint_key, space_key)
525 total_dp = result.get("dp", 1)
526 if "dp_shard" not in result:
527 # OP absent from the searched dimensions: fall back to the declared
528 # degree, which is what the parser used for the whole run.
529 fsdp_candidates = config.search_space.get("data_parallel_shard_degree", [1])
530 configured_fsdp = config.constraint.get("fixed_fsdp_degree")
531 result["dp_shard"] = int(configured_fsdp or fsdp_candidates[0])
532 # The yaml the search prices is AutoModels-shaped, whose FSDP domain is
533 # DP times CP: the shard may span it, and the trainer replicates the rest
534 # (MeshContext.build_meshs). Bounded by DP, a shard the search priced
535 # under CP was cut back and its replicas undercounted.
536 domain = total_dp * max(1, int(result.get("cp") or 1))
537 dp_shard = max(1, min(int(result["dp_shard"]), domain))
538 result["dp_shard"] = dp_shard
539 result["dp_replicate"] = max(1, domain // dp_shard)
540 return result
543def _recompute_result(nd_runner: Any, best_entry: tuple) -> Dict[str, Any]:
544 """The recompute the search chose for the best configuration, for the result.
546 Args:
547 nd_runner: The search, run with recompute "auto" or "per_layer".
548 best_entry: The best scored entry.
550 Returns:
551 ``activation_checkpoint``, the mode the trainer runs every layer
552 with: the chosen one, or ``full``, the policy the configuration was
553 scored with when there was nothing to choose. Under "per_layer",
554 ``activation_checkpoint_layers`` gives the layers that run another
555 mode, as the trainer's ``activation_checkpoint.layers`` states them,
556 where there are any: the resolved yaml writes them where the
557 installed trainer declares that field, and else runs every layer the
558 mode and logs them as advice (``_strategy_output``). With a choice
559 per layer possible,
560 ``recompute_per_layer`` also gives each layer's own fastest option of
561 its kind's front and the score and memory it would reach: what the
562 trainer would gain from running each layer its own way, switch by
563 switch. ``offloaded_layers`` names the layers a choice offloads, as
564 ``"first"`` or ``"first-last"``, where it offloads any: the plan
565 states them off, the trainer running no offload yet.
566 ``offloaded_gib`` gives, by the same names, the GiB each of those
567 layers moves to the host per micro-batch, and ``offloaded_share``
568 the share of what it keeps that is.
569 """
570 # pylint: disable=C0415
571 from hyper_parallel.auto_parallel.sapp_nd.recompute.candidate import offloaded_share, to_records, trainer_plan
572 choice = nd_runner.recompute_choices.get(best_entry[0])
573 mode, layers = trainer_plan(choice) if choice is not None else ("full", {})
574 result: Dict[str, Any] = {"activation_checkpoint": mode}
575 if layers:
576 result["activation_checkpoint_layers"] = layers
577 # Only a choice per layer offloads; one mode for every layer states no ranges of its own.
578 offloaded = [item for item in getattr(choice, "ranges", ()) if item.option.link_bandwidth]
579 if offloaded:
580 names = [str(item.first) if item.count == 1 else f"{item.first}-{item.first + item.count - 1}"
581 for item in offloaded]
582 result["offloaded_layers"] = names
583 result["offloaded_gib"] = {name: item.option.link_bandwidth / 2 ** 30 for name, item in zip(names, offloaded)}
584 result["offloaded_share"] = {name: offloaded_share(item.option) for name, item in zip(names, offloaded)}
585 per_layer, score = nd_runner.recompute_per_layer(best_entry[0])
586 if per_layer is not None:
587 result["recompute_per_layer"] = {
588 "score": float(score),
589 "memory_estimate_mb": float(per_layer.memory),
590 "ranges": to_records(per_layer),
591 }
592 return result
595def search_strategies(config: NormalizedConfig, offload: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]:
596 """Run the ND strategy search and return the optimal strategy.
598 This is the main entry point for end-to-end strategy search:
600 1. Validates required model fields.
601 2. Shapes the ``NormalizedConfig`` into the cost-model config ND
602 parses, as a mapping rather than a file.
603 3. Launches the ND search engine (:class:`Parallelize`).
604 4. Post-filters results against the user's candidate lists.
605 5. Returns the best strategy as a flat dictionary.
607 Args:
608 config: A fully populated ``NormalizedConfig`` from
609 :func:`read_search_config` or :func:`read_hp_yaml_config`.
610 ``config.estimator["ratios_file"]``, when set, names the ratios
611 file ``run_nd --write_ratios`` fits, which ND scores with
612 (``run_nd -s ... -c`` sets it); without it ND scores raw.
613 offload: With a choice of a recompute mode per layer, let each
614 stage's first layers run off and offload what they keep, over the
615 device's host link with these of its figures replaced
616 (:meth:`HostLink.of`), ``None`` for one left as the device states
617 it. ``None`` offloads nothing.
619 Returns:
620 A dict with keys ``dp``, ``tp``, ``pp``, ``cp``, ``ep``,
621 ``micro_batch_num``, ``memory_estimate_mb``, and ``score``.
623 Raises:
624 ValueError: If required fields are missing or no strategy is found,
625 or for *offload* without a choice of a mode per layer.
626 """
627 _validate_before_search(config)
629 hp_config = _build_hp_yaml_dict(config)
630 machine = _build_machine(config)
631 dims, candidate_dims = _resolve_search_dimensions(config)
633 import hyper_parallel.auto_parallel.sapp_nd.nd.parallelize as _Par # pylint: disable=C0415
634 from hyper_parallel.auto_parallel.sapp_nd.nd.common.derive import ( # pylint: disable=C0415
635 HYPER_SELECTIVE_REC_OP,
636 )
637 strategy = config.estimator.get("recompute_strategy")
638 auto = strategy in CHOSEN_RECOMPUTE
639 trainer = {
640 "auto_recompute": True,
641 # The search config may narrow the modes, as to leave out a mode the
642 # estimate prices faster than the device runs it.
643 "recompute_modes": tuple(config.estimator.get("recompute_modes")
644 or TRAINER_RECOMPUTE_MODES),
645 # Explicit legacy cost-model selective choices retain their switches;
646 # they are not inferred from a generic activation census.
647 "recompute_selective": dict(HYPER_SELECTIVE_REC_OP),
648 "recompute_mode_per_layer": strategy == "per_layer",
649 }
650 if offload is not None:
651 if strategy != "per_layer":
652 raise ValueError("offload is priced in a choice of a recompute mode per layer: give the search config "
653 "recompute: per_layer")
654 from hyper_parallel.auto_parallel.sapp_nd.nd.common.hardware import HostLink # pylint: disable=C0415
655 trainer.update(auto_offload=True, host_link=HostLink.of(machine.device.host_link, offload))
656 nd_runner = _Par.Parallelize(
657 "hyper_v2",
658 hp_config,
659 machine,
660 global_batch_size=config.constraint.get("global_batch_size", 0),
661 dimensions=dims,
662 **(trainer if auto else {}),
663 )
664 scored_space = nd_runner.run_generation_to_ordering(
665 yaml_folder=None,
666 threads_num=None,
667 top_num=None,
668 cache_file=config.estimator.get("ratios_file"),
669 )
671 if not scored_space:
672 raise ValueError("ND search returned no valid strategies.")
674 filtered = _post_filter(scored_space, config, candidate_dims)
675 if not filtered:
676 feasible = _filter_by_memory(scored_space, _memory_budget_gb(config))
677 if feasible:
678 raise ValueError(_no_candidate_match(feasible, config, candidate_dims))
679 lightest_gb = min(float(entry[1]) for entry in scored_space) / 1024.0
680 raise ValueError(
681 "No strategy fits the memory budget of "
682 f"{_memory_budget_gb(config):.1f} GB; the lightest strategy "
683 f"found needs {lightest_gb:.1f} GB. Raise "
684 "constraint.memory_limit_gb or widen the search space."
685 )
686 best = filtered[0]
687 result = _format_result(best, config)
688 if auto:
689 result.update(_recompute_result(nd_runner, best))
690 else:
691 # Without "auto" the search prices every candidate fully recomputed,
692 # whatever the search yaml says, so the trainer runs what was priced.
693 result["activation_checkpoint"] = "full"
695 logger.info(
696 "Optimal strategy found: dp=%(dp)s tp=%(tp)s pp=%(pp)s "
697 "cp=%(cp)s ep=%(ep)s mb_num=%(micro_batch_num)s "
698 "recompute=%(activation_checkpoint)s "
699 "mem=%(memory_estimate_mb).0f MB score=%(score).2e",
700 result,
701 )
702 return result