Agent Builder
shareAI-lab/learn-claude-code
Design and build AI agents for any domain. An agent skill from shareAI-lab/learn-claude-code.
Add detailed memory profiling prints throughout the training framework.
$ npx skills add mlc-ai/pith-train --skill add-memory-prints -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install mlc-ai/pith-train add-memory-prints --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/mlc-ai/pith-train.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/add-memory-prints .claude/skills/add-memory-prints && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "add-memory-prints" agent skill from https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-prints into .claude/skills/add-memory-prints/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "add-memory-prints", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-printsType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add mlc-ai/pith-train --skill add-memory-prints -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install mlc-ai/pith-train add-memory-prints --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/mlc-ai/pith-train.git skills-src && mkdir -p .agents/skills && cp -r skills-src/.agents/skills/add-memory-prints .agents/skills/add-memory-prints && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "add-memory-prints" agent skill from https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-prints into .agents/skills/add-memory-prints/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "add-memory-prints", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add mlc-ai/pith-train --skill add-memory-prints -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install mlc-ai/pith-train add-memory-prints --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/mlc-ai/pith-train.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/.agents/skills/add-memory-prints .cursor/skills/add-memory-prints && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "add-memory-prints" agent skill from https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-prints into .cursor/skills/add-memory-prints/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "add-memory-prints", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/mlc-ai/pith-train.git --path .agents/skills/add-memory-prints--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add mlc-ai/pith-train --skill add-memory-prints -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install mlc-ai/pith-train add-memory-prints --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/mlc-ai/pith-train.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/.agents/skills/add-memory-prints .gemini/skills/add-memory-prints && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "add-memory-prints" agent skill from https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-prints into .gemini/skills/add-memory-prints/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "add-memory-prints", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install mlc-ai/pith-train add-memory-printsInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add mlc-ai/pith-train --skill add-memory-prints -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/mlc-ai/pith-train.git skills-src && mkdir -p .github/skills && cp -r skills-src/.agents/skills/add-memory-prints .github/skills/add-memory-prints && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "add-memory-prints" agent skill from https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-prints into .github/skills/add-memory-prints/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "add-memory-prints", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add mlc-ai/pith-train --skill add-memory-prints -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install mlc-ai/pith-train add-memory-prints --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/mlc-ai/pith-train.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/.agents/skills/add-memory-prints .opencode/skills/add-memory-prints && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "add-memory-prints" agent skill from https://github.com/mlc-ai/pith-train/tree/main/.agents/skills/add-memory-prints into .opencode/skills/add-memory-prints/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "add-memory-prints", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
add-memory-printsAdd detailed memory profiling prints throughout the training framework.
Add Memory Prints is an agent skill from mlc-ai/pith-train. Add detailed memory profiling prints throughout the training framework. Instruments distributed setup, model creation, checkpoint loading, pipeline scheduling, per-layer activations, saved tensor profiling, expert MLP internals, and memory snapshot dumps. Use when user asks to "add memory prints", "instrument memory", "profile memory", "memory breakdown", or "debug memory".
Its SKILL.md is about 6.2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.
It sits in AI & LLM Engineering. The repository describes itself as: Compact and Agent-Native MoE Training System. The licence is Apache-2.0.
3 steps, taken from the first numbered list in SKILL.md.
Read from SKILL.md and the folder at commit c7c8b1d. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Shell commands in SKILL.md call:
ruffFrom the folder's file list and the shell code blocks in SKILL.md.
No URLs in SKILL.md.
From URLs in SKILL.md, links to its own repository left out.
Names no API keys, tokens, secrets or passwords.
From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Add Memory Prints loads about 6.2k tokens when it runs. Until then it costs about 99 tokens; SKILL.md has 1,190 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check found no risky patterns in SKILL.md.
Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.
The full file from mlc-ai/pith-train at commit c7c8b1d, republished under its Apache-2.0 licence (© mlc-ai). 1,190 words, ~6,163 tokens.
.claude/skills/add-memory-prints/SKILL.md (or your agent's skills folder).Add comprehensive memory profiling instrumentation to the pithtrain training framework. This skill adds 7 groups of memory prints across 6 files, covering every phase from distributed init through the pipeline loop.
Parse the following from $ARGUMENTS:
pithtrain/models/ (e.g., qwen3-moe maps to pithtrain/models/qwen3_moe.py).{0}): Comma-separated GPU global ranks to print on. E.g., --ranks 3,14 becomes the Python set {3, 14}. If not provided, defaults to {0}.Throughout this document, RANKS means the parsed rank set (e.g., {3, 14}), and DETAIL_LAYERS means the parsed or auto-selected layer indices tuple (e.g., (5, 6)).
All edits are observation-only:
_lmem() and _mem_gb() call torch.cuda.synchronize() + read memory_allocated(). No tensor modification._SavedTensorsProfiler uses saved_tensors_hooks with a pack function that returns the tensor unchanged.return self.down_proj(silu_mul(g, u), ...) into gu = silu_mul(g, u); out = self.down_proj(gu, ...); return out — functionally identical._mem_gb, _lmem, _layer_mem_profile, _setup_mem, or memory_profiling in the codebase. If found, ask the user whether to update ranks/layers or skip.$ARGUMENTS for model, ranks, and detail layers.pithtrain/pipeline/dualpipev.pyAdd right before class DualPipeV:
def _mem_gb() -> float:
"""Return current CUDA memory allocated in GiB."""
return torch.cuda.memory_allocated() / 1024**3
def _mem_detail() -> str:
"""Return allocated, cached-pool, and non-pytorch memory in GiB."""
free, total = torch.cuda.mem_get_info()
allocated = torch.cuda.memory_allocated()
reserved = torch.cuda.memory_reserved()
G = 1024**3
cached = reserved - allocated
non_pytorch = total - free - reserved
return f"alloc={allocated / G:.2f} cached={cached / G:.2f} non-pt={non_pytorch / G:.2f}"In DualPipeV.__init__, add after self.comm_stream = ...:
self.memory_profiling = True # Set to True to enable per-step memory loggingpithtrain/pipeline/execution.pyAdd after imports, before any function definitions:
# -- Per-layer activation profiling --
_layer_mem_profile = False
_layer_mem_ranks = RANKS
class _SavedTensorsProfiler:
"""Context manager that logs tensors saved by autograd, distinguishing weights from activations."""
def __init__(self, layer_idx: int, stage_name: str, weight_data_ptrs: set):
self._layer_idx = layer_idx
self._stage_name = stage_name
self._weight_data_ptrs = weight_data_ptrs
self._log: list[str] = []
self._act_bytes = 0
self._wt_bytes = 0
def _pack(self, t: torch.Tensor) -> torch.Tensor:
nbytes = t.nelement() * t.element_size()
is_wt = t.data_ptr() in self._weight_data_ptrs
tag = "weight" if is_wt else "activ"
self._log.append(
f" saved ({tag}): {tuple(t.shape)} {t.dtype} ({nbytes / 1024**2:.1f} MB)"
)
if is_wt:
self._wt_bytes += nbytes
else:
self._act_bytes += nbytes
return t
def __enter__(self):
self._ctx = torch.autograd.graph.saved_tensors_hooks(self._pack, lambda t: t)
self._ctx.__enter__()
return self
def __exit__(self, *args):
self._ctx.__exit__(*args)
def print_summary(self):
rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
if rank not in _layer_mem_ranks:
return
hdr = f"layer{self._layer_idx} {self._stage_name} saved tensors"
print(f"[rank={rank}] {hdr}:", flush=True)
for line in self._log:
print(f"[rank={rank}] {line}", flush=True)
print(
f"[rank={rank}] activ={self._act_bytes / 1024**2:.1f} MB, "
f"weight={self._wt_bytes / 1024**2:.1f} MB, "
f"total={len(self._log)} tensors",
flush=True,
)
def _lmem(label: str) -> None:
"""Print memory at a layer-internal checkpoint."""
if not _layer_mem_profile:
return
rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
if rank not in _layer_mem_ranks:
return
torch.cuda.synchronize()
alloc = torch.cuda.memory_allocated() / 1024**3
print(f"[rank={rank}] {label}: alloc={alloc:.2f}", flush=True)pithtrain/modules/training.pyAdd before setup_model:
def _setup_mem(label: str) -> None:
"""Print CUDA memory at a setup checkpoint."""
if torch.distributed.get_rank() in RANKS:
torch.cuda.synchronize()
G = 1024**3
alloc = torch.cuda.memory_allocated()
reserved = torch.cuda.memory_reserved()
free, total = torch.cuda.mem_get_info()
cached = reserved - alloc
non_pytorch = total - free - reserved
print(
f"[rank={torch.distributed.get_rank()}] setup_model | {label}: "
f"alloc={alloc / G:.2f} cached={cached / G:.2f} non-pt={non_pytorch / G:.2f}",
flush=True,
)pithtrain/modules/distributed.py)setup_default_process_groupImportant: this runs BEFORE init_process_group, so torch.distributed.get_rank() is not available, and distributed.rank is not published until setup_device_mesh. Use the device_id parameter for the rank guard.
torch.cuda.mem_get_info reads the current device, which nothing has set this early, so the probe sets it itself; setup_device_mesh sets it again later, harmlessly. Add a memory probe before and after init_process_group:
# Probe: isolate CUDA context cost from NCCL communicator init
torch.cuda.set_device(device_id)
torch.cuda.synchronize()
_free0, _total = torch.cuda.mem_get_info()
_non_pt0 = _total - _free0
G = 1024**3
# ... existing init_process_group code ...
torch.cuda.synchronize()
_free1, _ = torch.cuda.mem_get_info()
_non_pt1 = _total - _free1
if device_id in RANKS:
print(
f"[rank={torch.distributed.get_rank()}] init_process_group | "
f"cuda_ctx={_non_pt0 / G:.2f} "
f"after_nccl_world={_non_pt1 / G:.2f} "
f"nccl_world_cost={(_non_pt1 - _non_pt0) / G:.2f}",
flush=True,
)setup_device_meshBefore and after init_device_mesh:
torch.cuda.synchronize()
_free_before, _total = torch.cuda.mem_get_info()
_non_pt_before = _total - _free_before
# ... existing init_device_mesh code ...
torch.cuda.synchronize()
_free_after, _ = torch.cuda.mem_get_info()
_non_pt_after = _total - _free_after
G = 1024**3
if device_id in RANKS:
print(
f"[rank={distributed.rank}] init_device_mesh | "
f"non-pt={_non_pt_after / G:.2f} "
f"mesh_cost={(_non_pt_after - _non_pt_before) / G:.2f}",
flush=True,
)pithtrain/modules/training.py)Add _setup_mem(...) calls at these 5 points in setup_model:
modules = [] — _setup_mem("before model creation")_setup_mem("after module[0] creation")_setup_mem("after module[1] creation")init_weights loop — _setup_mem("after init_weights")apply_fsdp(...) — _setup_mem("after apply_fsdp")pithtrain/pipeline/dualpipev.py)This is the most complex group. All insertions go into DualPipeV.step(). The code below shows every insertion with its exact anchor point.
4A: Profiling flag setup — insert after the first-rank micro-batch setup (self.objective = objective), before # Step 1:
_profiling = self.memory_profiling and distributed.rank in RANKS
if _profiling:
torch.cuda.synchronize()
_m0 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] Before pipeline: {_m0:.2f} GiB | {_mem_detail()}",
flush=True,
)4B: Step 1 (nF0) — modify the existing loop body. The original loop is:
for i in range(step_1):
self._forward_chunk(0)Replace with:
for i in range(step_1):
if _profiling and i == 1:
import pithtrain.pipeline.execution as _mod
_mod._layer_mem_profile = True
self._forward_chunk(0)
if _profiling and i == 1:
_mod._layer_mem_profile = False
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step1 F0 i={i}: {_mem_gb():.2f} GiB (+{_mem_gb() - _m0:.2f}) | {_mem_detail()}",
flush=True,
)After the loop, before Step 2:
if _profiling:
torch.cuda.synchronize()
_m1 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] After Step1 ({step_1} F0): {_m1:.2f} GiB (+{_m1 - _m0:.2f}) | {_mem_detail()}",
flush=True,
)4C: Step 2 (nF0F1) — modify the loop body. Original:
for i in range(step_2):
self._forward_chunk(0, recv=False, send=False)
self._recv_forward(0)
self._forward_chunk(1, send=(not self.is_last_pp_rank) or (i < step_2 - 1))
self._send_forward(0)Replace with:
for i in range(step_2):
self._forward_chunk(0, recv=False, send=False)
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step2 i={i} forward_chunk(0): {_mem_gb():.2f} GiB (+{_mem_gb() - _m0:.2f}) | {_mem_detail()}",
flush=True,
)
self._recv_forward(0)
if _profiling and i == 0:
import pithtrain.pipeline.execution as _mod
_mod._layer_mem_profile = True
self._forward_chunk(1, send=(not self.is_last_pp_rank) or (i < step_2 - 1))
if _profiling and i == 0:
_mod._layer_mem_profile = False
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step2 i={i} forward_chunk(1): {_mem_gb():.2f} GiB (+{_mem_gb() - _m0:.2f}) | {_mem_detail()}",
flush=True,
)
self._send_forward(0)After the loop:
if _profiling:
torch.cuda.synchronize()
_m2 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] After Step2 ({step_2} F0F1): {_m2:.2f} GiB (+{_m2 - _m0:.2f}) | {_mem_detail()}",
flush=True,
)4D: Step 3 (nB1W1F1) — modify the loop body. Original:
for i in range(step_3):
self._backward_chunk(1, enable_zb=True)
self._recv_forward(1)
self._weight_chunk()
self._forward_chunk(1, recv=False)Replace with:
for i in range(step_3):
if _profiling:
torch.cuda.synchronize()
_ms3 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step3 i={i} before B1: {_ms3:.2f} GiB | {_mem_detail()}",
flush=True,
)
self._backward_chunk(1, enable_zb=True)
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step3 i={i} after B1: {_mem_gb():.2f} GiB (delta={_mem_gb() - _ms3:+.2f}) | {_mem_detail()}",
flush=True,
)
self._recv_forward(1)
self._weight_chunk()
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step3 i={i} after W1: {_mem_gb():.2f} GiB (delta={_mem_gb() - _ms3:+.2f}) | {_mem_detail()}",
flush=True,
)
self._forward_chunk(1, recv=False)
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step3 i={i} after F1: {_mem_gb():.2f} GiB (delta={_mem_gb() - _ms3:+.2f}) | {_mem_detail()}",
flush=True,
)After the loop:
if _profiling:
torch.cuda.synchronize()
_m3 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] After Step3 ({step_3} B1W1F1): {_m3:.2f} GiB (+{_m3 - _m0:.2f}) | {_mem_detail()}",
flush=True,
)4E: Step 4 (nF0B1F1B0) — after the last self._forward_backward_chunk(1, 0) inside the loop (there is one at the end of every iteration), add:
if _profiling:
torch.cuda.synchronize()
print(
f"[rank={distributed.rank} pp={pp_rank}] Step4 i={i}: {_mem_gb():.2f} GiB | {_mem_detail()}",
flush=True,
)After the loop:
if _profiling:
torch.cuda.synchronize()
_m4 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] After Step4 ({step_4} F0B1F1B0): {_m4:.2f} GiB | {_mem_detail()}",
flush=True,
)4F: Steps 5-7 — no prints needed.
4G: After Step 8 — after assert WeightGradStore.funcs_queue.empty(), before self._commit_and_wait_comm():
if _profiling:
torch.cuda.synchronize()
_m8 = _mem_gb()
print(
f"[rank={distributed.rank} pp={pp_rank}] After Step8 (end of pipeline): {_m8:.2f} GiB | {_mem_detail()}",
flush=True,
)pithtrain/pipeline/execution.py + model file)layer_forward() (execution.py)layer_forward(layer, hidden_states, rotary_posemb, layer_record, cu_seqlens=None) runs the five stages in order, each under its own # Stage N. comment block. At the top of the function, before # Stage 1., add:
_do_lmem = _layer_mem_profile and layer.idx in DETAIL_LAYERS
_do_saved = _layer_mem_profile and layer.idx in DETAIL_LAYERS
_wt_ptrs: set = set()
if _do_saved:
_wt_ptrs = {p.data_ptr() for p in layer.parameters()}Then instrument each stage:
Stage 1 — wrap the layer.forward_stage1(...) call:
if _do_saved:
_prof = _SavedTensorsProfiler(layer.idx, "stage1", _wt_ptrs)
with _prof:
dispatch_tokens, residual, routing = layer.forward_stage1(next_hidden_states, rotary_posemb, cu_seqlens)
_prof.print_summary()
else:
dispatch_tokens, residual, routing = layer.forward_stage1(next_hidden_states, rotary_posemb, cu_seqlens)After the Stage 1 record is populated: if _do_lmem: _lmem(f"layer{layer.idx} after stage1 (forward_stage1: attn + gate + dispatch_prep)")
Stage 2 — after the nvtx.range_pop() closing Stage 2: if _do_lmem: _lmem(f"layer{layer.idx} after stage2 (dispatch a2a)")
Stage 3 — same wrapping pattern as Stage 1, using _SavedTensorsProfiler(layer.idx, "stage3", _wt_ptrs) around the layer.forward_stage3(...) call:
if _do_saved:
_prof = _SavedTensorsProfiler(layer.idx, "stage3", _wt_ptrs)
with _prof:
moe_outs = layer.forward_stage3(gathered_tokens, routing.expert_idxs if has_experts else None, routing.expand_idx if has_experts else None)
_prof.print_summary()
else:
moe_outs = layer.forward_stage3(gathered_tokens, routing.expert_idxs if has_experts else None, routing.expand_idx if has_experts else None)After: if _do_lmem: _lmem(f"layer{layer.idx} after stage3 (forward_stage3)")
Stage 4 — after the nvtx.range_pop() closing Stage 4: if _do_lmem: _lmem(f"layer{layer.idx} after stage4 (combine a2a)")
Stage 5 — same wrapping pattern around the layer.forward_stage5(...) call with _SavedTensorsProfiler(layer.idx, "stage5", _wt_ptrs):
if _do_saved:
_prof = _SavedTensorsProfiler(layer.idx, "stage5", _wt_ptrs)
with _prof:
hidden_states = layer.forward_stage5(moe_outs, moe_local_idxs, topk_weight, residual)
_prof.print_summary()
else:
hidden_states = layer.forward_stage5(moe_outs, moe_local_idxs, topk_weight, residual)After: if _do_lmem: _lmem(f"layer{layer.idx} after stage5 (forward_stage5)")
forward_stage1 (model file)forward_stage1 runs the compiled forward_stage1_compute helper (LN + attention + LN + router gate) and then prepare_dispatch. Add at the top:
from pithtrain.pipeline.execution import _layer_mem_profile, _lmem
_do = _layer_mem_profile and self.idx in DETAIL_LAYERSAdd _lmem prints:
forward_stage1_compute(...) call: if _do: _lmem(f" layer{self.idx} stage1: before forward_stage1_compute")forward_stage1_compute(...) call: if _do: _lmem(f" layer{self.idx} stage1: after forward_stage1_compute (LN+Attn+LN+gate)")prepare_dispatch(...): if _do: _lmem(f" layer{self.idx} stage1: after dispatch_prep dispatch={tuple(dispatch_tokens.shape)}")The router gate runs inside the compiled forward_stage1_compute, so its allocation is captured by the "after forward_stage1_compute" probe rather than a separate print.
forward_stage3 (model file)Add at the top:
from pithtrain.pipeline.execution import _layer_mem_profile, _lmem
_do = _layer_mem_profile and self.idx in DETAIL_LAYERSAdd _lmem prints:
padded_index_gather(gathered_tokens, expand_idx) gather (ep_size > 1 branch): if _do: _lmem(f" layer{self.idx} stage3: before expand gather gathered={tuple(gathered_tokens.shape)}")if _do: _lmem(f" layer{self.idx} stage3: after expand gather expanded={tuple(gathered_tokens.shape)}")scatter_for_grouped_gemm: if _do: _lmem(f" layer{self.idx} stage3: after scatter output_tokens={tuple(output_tokens.shape)}")self.mlp.experts(...): if _do: _lmem(f" layer{self.idx} stage3: after experts outs={tuple(outs.shape)}")padded_index_gather(outs, reverse_shuffle_idxs): if _do: _lmem(f" layer{self.idx} stage3: after unshuffle outs={tuple(outs.shape)}")forward_stage3 returns padded_index_gather(outs, reverse_shuffle_idxs) directly; assign it to outs first so the unshuffle print has a value to report before the return.
Critical: Also pass _do_mem=_do to the experts forward call. Change:
outs = self.mlp.experts(output_tokens, grouped_mm_offs, ks=ks, ks_tensor=ks_tensor)to:
outs = self.mlp.experts(output_tokens, grouped_mm_offs, ks=ks, ks_tensor=ks_tensor, _do_mem=_do)forward (model file)_do_mem: bool = False parameter to the forward() signature.from pithtrain.pipeline.execution import _lmem at the top.if _do_mem::gate_proj: shape of input xgate_proj: shape of gup_proj: shape of usilu_mul(g, u): shape of gudown_proj: shape of outreturn self.down_proj(silu_mul(g, u), **kwargs) to:gu = silu_mul(g, u)
if _do_mem:
_lmem(f" experts: after silu_mul gu={tuple(gu.shape)}")
out = self.down_proj(gu, **kwargs)
if _do_mem:
_lmem(f" experts: after down_proj out={tuple(out.shape)}")
return outforward_prolog / forward_epilog (model file)Prolog (embed) and epilog (norm + lm_head) compute live in the model's forward_prolog and forward_epilog methods, which the pipeline invokes on the first and last stage respectively. Add the import in each method that uses it:
from pithtrain.pipeline.execution import _layer_mem_profile, _lmemThen:
forward_prolog, after embedding the tokens (assign to a local, print, then return): if _layer_mem_profile: _lmem("after prolog (embed_tokens)")forward_epilog, at the top before self.norm(...): if _layer_mem_profile: _lmem("before epilog (norm + lm_head)")forward_epilog, after self.norm(...): if _layer_mem_profile: _lmem("after norm, before lm_head")forward_epilog, after self.lm_head(...): if _layer_mem_profile: _lmem("after lm_head")pithtrain/tasks/pretrain_lm.py)In load_checkpoint, after dcp.load(...):
rank = torch.distributed.get_rank()
if rank in RANKS:
torch.cuda.synchronize()
optim_mem = sum(
(s._local_tensor if isinstance(s, DTensor) else s).nelement()
* (s._local_tensor if isinstance(s, DTensor) else s).element_size()
for state in optimizer.state.values()
for s in state.values()
if isinstance(s, torch.Tensor)
)
G = 1024**3
alloc = torch.cuda.memory_allocated()
reserved = torch.cuda.memory_reserved()
free, total = torch.cuda.mem_get_info()
cached = reserved - alloc
non_pytorch = total - free - reserved
print(
f"[rank={rank}] load_ckpt | optimizer state: {optim_mem / G:.2f} GiB "
f"({len(optimizer.state)} param entries) | "
f"alloc={alloc / G:.2f} cached={cached / G:.2f} non-pt={non_pytorch / G:.2f}",
flush=True,
)Ensure DTensor is imported: from torch.distributed.tensor import DTensor. Check if it's already imported before adding.
pithtrain/tasks/pretrain_lm.py)In train_step, instrument the first training step with a full memory timeline snapshot.
Before the forward/backward call (after model.train()):
_mem_profile = step == 0
_mem_snapshot = _mem_profile and torch.distributed.get_rank() in RANKS
if _mem_profile:
model.memory_profiling = True
if _mem_snapshot:
torch.cuda.memory._record_memory_history(max_entries=1048576)Important: if the file already has torch.cuda.memory._record_memory_history for the configurable profiler (memory_profile_start), do NOT conflict with it. The snapshot code above is separate — it runs on step 0 unconditionally, while the configurable profiler starts at a user-specified step.
Wrap model.step(...) in try/except:
try:
objective_outputs = model.step(microbatches, objective)
except torch.OutOfMemoryError:
if _mem_snapshot:
snapshot = torch.cuda.memory._snapshot()
from pickle import dump
snapshot_path = f"/tmp/memory_snapshot_rank{torch.distributed.get_rank()}.pickle"
with open(snapshot_path, "wb") as f:
dump(snapshot, f)
print(f"[rank={torch.distributed.get_rank()}] Memory snapshot saved to {snapshot_path}")
torch.cuda.memory._record_memory_history(enabled=None)
raiseAfter the model.step call (before optimizer step):
if _mem_snapshot:
snapshot = torch.cuda.memory._snapshot()
from pickle import dump
snapshot_path = f"/tmp/memory_snapshot_rank{torch.distributed.get_rank()}_step0.pickle"
with open(snapshot_path, "wb") as f:
dump(snapshot, f)
print(f"[rank={torch.distributed.get_rank()}] Memory snapshot saved to {snapshot_path}")
torch.cuda.memory._record_memory_history(enabled=None)
if _mem_profile:
if hasattr(model, "memory_profiling"):
model.memory_profiling = Falsepithtrain/pipeline/execution.py — Groups 1B, 5Apithtrain/pipeline/dualpipev.py — Groups 1A, 4pithtrain/models/<model>.py — Groups 5B, 5C, 5D, 5Epithtrain/modules/distributed.py — Group 2pithtrain/modules/training.py — Groups 1C, 3pithtrain/tasks/pretrain_lm.py — Groups 6, 7Run ruff check --fix and ruff format on all modified files to ensure code style compliance.
© mlc-ai, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
Just SKILL.md in .agents/skills/add-memory-prints of mlc-ai/pith-train.
Open the folder on GitHubat commit c7c8b1d
Add Memory Prints next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Add Memory Prints this skillmlc-ai/pith-train | 355 | — | ~6.2k | Automated safety check: Pass | Apache-2.0 | |
| Agent BuildershareAI-lab/learn-claude-code | 78k | 5 repos | ~1.2k | Automated safety check: Pass | MIT | |
| Add Uint Supportpytorch/pytorch | 104k | 2 repos | ~2.3k | Automated safety check: Pass | Custom licence | |
| LLM Benchmarking with lm-evaluation-harnessOrchestra-Research/AI-Research-SKILLs | 13k | 8 repos | ~3k | Automated safety check: Pass | MIT | |
| Segment Anything Model GuideOrchestra-Research/AI-Research-SKILLs | 13k | 8 repos | ~3.3k | Automated safety check: Pass | MIT | |
| 1passwordtrpc-group/trpc-agent-go | 1.9k | 14 repos | ~656 | Automated safety check: Pass | Apache-2.0 |
shareAI-lab/learn-claude-code
Design and build AI agents for any domain. An agent skill from shareAI-lab/learn-claude-code.
pytorch/pytorch
Add unsigned integer (uint) type support to PyTorch operators by updating ATDISPATCH macros.
Orchestra-Research/AI-Research-SKILLs
Runs lm-evaluation-harness to benchmark language models on academic suites such as MMLU, GSM8K and HumanEval, compare models and track training checkpoints.
Orchestra-Research/AI-Research-SKILLs
Guide to using Meta's Segment Anything Model for zero-shot image segmentation with point, box or mask prompts, or automatic mask generation.
trpc-group/trpc-agent-go
Set up and use 1Password CLI (op). An agent skill from trpc-group/trpc-agent-go.
jarrodwatts/claude-code-config
Transforms workflow to use Manus-style persistent markdown files for planning, progress tracking, and knowledge storage.
mlc-ai/pith-train
Query a captured PithTrain Nsight Systems profile to measure compute/communication overlap, locate exposed comm by DualPipeV stage, and inspect per-rank stream behavior.
mlc-ai/pith-train
Capture a Nsight Systems (.nsys-rep) profile of a short PithTrain run for performance analysis.
mlc-ai/pith-train
Validates that code changes do not break training correctness by comparing loss deltas against a base-vs-base run-to-run envelope.
mlc-ai/pith-train
Measures the throughput difference between two branches with force-balanced routing.
mlc-ai/pith-train
Set up the minimal set of artifacts (tokenized DCLM corpus shard + released HuggingFace checkpoint converted to DCP) required to benchmark, profile, or regression-test a MoE model in PithTrain.
mlc-ai/pith-train
Adds support for a new MoE language model to PithTrain. An agent skill from mlc-ai/pith-train.
Categories
Add detailed memory profiling prints throughout the training framework. Add Memory Prints is an agent skill from mlc-ai/pith-train. Add detailed memory profiling prints throughout the training framework.
Add Memory Prints fits situations like: user asks to add memory prints; instrument memory; memory breakdown.
Run `npx skills add mlc-ai/pith-train --skill add-memory-prints -a claude-code`. Or copy the skill folder (.agents/skills/add-memory-prints in mlc-ai/pith-train) into .claude/skills/add-memory-prints in your project. Claude Code loads it when a task matches its description.
Run `npx skills add mlc-ai/pith-train --skill add-memory-prints -a codex`. Or copy the skill folder (.agents/skills/add-memory-prints in mlc-ai/pith-train) into .agents/skills/add-memory-prints in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add mlc-ai/pith-train --skill add-memory-prints -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/add-memory-prints, .gemini/skills/add-memory-prints, .github/skills/add-memory-prints and .opencode/skills/add-memory-prints in your project.
Going by SKILL.md and its folder, Add Memory Prints needs the command-line tools its instructions call (ruff). Our summary lists: Python 3.
SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.
Add Memory Prints is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 6.2k tokens (SKILL.md is roughly 25k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.
Skills that share tags, products or a category with Add Memory Prints: Agent Builder (shareAI-lab/learn-claude-code, 78k stars), Add Uint Support (pytorch/pytorch, 104k stars), LLM Benchmarking with lm-evaluation-harness (Orchestra-Research/AI-Research-SKILLs, 13k stars) and Segment Anything Model Guide (Orchestra-Research/AI-Research-SKILLs, 13k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
mlc-ai (a GitHub organization) maintains it in mlc-ai/pith-train, which has 355 GitHub stars. The repository holds 10 skills in this directory. The repository was last updated on October 4, 2026.
Source: mlc-ai/pith-train on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.