Repository navigation
[WIP]add dynamic shape support and size specialization for dynamic shapes #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
honghaowang25
wants to merge
2
commits into
graph_automodel_adapt
Choose a base branch
from
0929_newdynamic
base: graph_automodel_adapt
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 71 additions & 0 deletions
71
hyper_parallel/compile/examples/automodel_text_graph/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| # Dynamic token batching with graph-mode text training | ||
|
|
||
| This example runs the standard TextTrainer + BaseTrainer + GraphCompiler path | ||
| with TP2 + FSDP2 on four NPUs. It uses an online iterable dataset, | ||
| TokenBatchLoader and dense packed attention. The model directory provides the | ||
| model configuration and tokenizer; the text generator needs no downloaded dataset. | ||
|
|
||
| ## Run ordinary training | ||
|
|
||
| From the repository root in a torch + torch_npu environment: | ||
|
|
||
| ```bash | ||
| python -m hyper_parallel.compile.examples.automodel_text_graph.prepare_dynamic_text | ||
|
|
||
| ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 bash \ | ||
| hyper_parallel/compile/examples/automodel_text_graph/run.sh \ | ||
| hyper_parallel/compile/examples/automodel_text_graph/train_online_lm_graph_dynamic_tp2_fsdp2.yaml \ | ||
| --model.pretrained_model_name_or_path=/path/to/Qwen3-0.6B | ||
| ``` | ||
|
|
||
| The YAML enables `compile.dynamic: true`; manual dimension annotations are | ||
| optional. Packing combines variable numbers of records into `[1, packed_length]`, | ||
| so the sequence dimension changes while the physical batch dimension remains one. | ||
| The iterable dataset avoids limiting raw records before token packing. | ||
| Replace `dataset.data_path` to use another plaintext source. | ||
|
|
||
| This functional smoke run uses random initialization (`model.load_base_model: false`) | ||
| and FP32 model parameters. Graph FSDP shards parameters on first capture; | ||
| separate optimizer master copies constructed earlier can retain the full shape. | ||
| That optimizer combination is not exercised by this example. | ||
|
|
||
| `run.sh` defaults to `scripts/train_lm.py`. It accepts a YAML path followed by | ||
| existing CLI overrides. Set `PYTHON=/path/to/venv/bin/python` to select the | ||
| interpreter, and use `MASTER_PORT`, `NPROC_PER_NODE` and `OUTPUT_DIR` for launcher | ||
| settings. The default YAML remains the indexed/static example. The output is a | ||
| normal training log; this entry does not export a separate per-rank audit JSON. | ||
|
|
||
| ## Optional size specialization | ||
|
|
||
| Add these overrides to the dynamic training command: | ||
|
|
||
| ```bash | ||
| '--compile.compile_sizes=[116,120,127]' \ | ||
| --compile.compile_size_input=model_inputs.input_ids \ | ||
| --compile.compile_size_dim=1 | ||
| ``` | ||
|
|
||
| The first execution uses the general graph. Later configured sizes generate an | ||
| FX variant once per complete input metadata signature and reuse it. Other sizes, | ||
| or new signatures at the cache limit, continue using the general graph. | ||
| `compile.max_specializations` defaults to 8. Omit `compile_sizes` to disable variants. | ||
| A different tokenizer or dataset can change which packed lengths recur. | ||
|
|
||
| Generation binds shape expressions in the post-pass FX graph. It does not | ||
| recapture the model, shard parameters again, execute collectives during generation | ||
| or invoke an Inductor/NPU kernel compiler. Tensor values, token counts and model | ||
| weights remain runtime inputs. This is a functionality example, not a throughput | ||
| or convergence benchmark. | ||
|
|
||
| ## Regression tests and implementation notes | ||
|
|
||
| Small-model shape/gradient and dispatch checks live in the existing CPU UT: | ||
|
|
||
| ```bash | ||
| python -m pytest tests/ut/compile/test_dynamic_shapes.py \ | ||
| tests/ut/compile/test_size_specialization.py -q | ||
| ``` | ||
|
|
||
| These tests check eager loss/gradient parity, graph reuse, guards and multiple hot | ||
| sizes. CPU UT and mocked communication do not substitute for real NPU training. | ||
| Dynamic PP and arbitrary data-dependent shapes remain outside the supported path. |
42 changes: 42 additions & 0 deletions
42
hyper_parallel/compile/examples/automodel_text_graph/prepare_dynamic_text.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # Copyright 2026 Huawei Technologies Co., Ltd | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================ | ||
| """Prepare deterministic plaintext records for dynamic token-budget batching.""" | ||
|
|
||
| import argparse | ||
| import json | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """Write locally generated text of several lengths; no download is required.""" | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument("--output", default="output/automodel_text_graph/dynamic_text.jsonl") | ||
| args = parser.parse_args() | ||
| output = Path(args.output) | ||
| output.parent.mkdir(parents=True, exist_ok=True) | ||
| lengths = (3, 7, 11, 17, 23, 31, 43, 59, 73, 89, 101, 113) | ||
| records = [ | ||
| {"text": "Training example " + str(index) + ": " + " ".join( | ||
| ["language", "models", "learn", "from", "text"][token % 5] | ||
| for token in range(lengths[index % len(lengths)]) | ||
| )} | ||
| for index in range(384) | ||
| ] | ||
| output.write_text("".join(json.dumps(record) + "\n" for record in records), encoding="utf-8") | ||
| print(f"Wrote {len(records)} variable-length records to {output}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
换个名