Inspect · Source & workspace
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val>Gemini 3.7 Flash · RL
Qwen3-1.7B online GRPO 2dev · Joint Optimization
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentGemini 3.7 Flash · 153 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val>Requested file and log inspection related to task requirements.
2 calls · #0002–#0003
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0004–#0004
Read <path>Requested file and log inspection related to reward & policy updates.
1 call · #0005–#0005
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0006–#0006
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0007–#0007
Read <path>Requested file and log inspection related to source & workspace.
4 calls · #0008–#0011
Read <path>Requested environment setup or inspection, source searches and script or workload execution related to source & workspace.
2 calls · #0012–#0013
envgrep <val>bash <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0014–#0014
bash <script>Requested workspace inspection, source searches and file and log inspection related to source & workspace.
19 calls · #0015–#0033
Find <pattern>Search <pattern> <path>Read <path>List <path>Requested file and log inspection related to benchmark & validation setup.
6 calls · #0034–#0039
Read <path>Requested file and log inspection related to task requirements.
1 call · #0040–#0040
Read <path>Requested source searches, file and log inspection and workspace inspection related to source & workspace.
13 calls · #0041–#0053
Search <pattern> <path>Read <path>Find <pattern>List <path>Requested file and log inspection related to reward & policy updates.
1 call · #0054–#0054
Read <path>Requested runtime inspection related to device memory.
1 call · #0055–#0055
npu-smi infoRequested workspace inspection related to source & workspace.
1 call · #0056–#0056
List <path>Requested file and log inspection related to task requirements.
1 call · #0057–#0057
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0058–#0058
Read <path>Requested source searches related to source & workspace.
1 call · #0059–#0059
Search <pattern> <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0060–#0060
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0061–#0061
Read <path>Requested source searches and file and log inspection related to rollout generation.
2 calls · #0062–#0063
Search <pattern> <path>Read <path>Requested source searches, workspace inspection and file and log inspection related to source & workspace.
4 calls · #0064–#0067
Search <pattern> <path>Find <pattern>Read <path>Requested source searches related to checkpoints & weight state.
1 call · #0068–#0068
Search <pattern> <path>Requested file and log inspection and source searches related to source & workspace.
3 calls · #0069–#0071
Read <path>Search <pattern> <path>Requested file and log inspection related to checkpoints & weight state.
3 calls · #0072–#0074
Read <path>Requested code edits related to source & workspace.
1 call · #0075–#0075
Write <path>Requested workspace file updates related to source & workspace.
1 call · #0076–#0076
mkdir -p <path>touch <path>Requested source searches and file and log inspection related to source & workspace.
3 calls · #0077–#0079
Search <pattern> <path>Read <path>cat <script>Requested script or workload execution related to source & workspace.
1 call · #0080–#0080
bash <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0081–#0081
bash <script>Requested file and log inspection related to benchmark & validation setup.
1 call · #0082–#0082
Read <path>Requested source searches and file and log inspection related to source & workspace.
3 calls · #0083–#0085
Search <pattern> <path>Read <path>cat <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0086–#0086
bash <script>Requested workspace file updates related to source & workspace.
1 call · #0087–#0087
rm -f <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0088–#0088
bash <script>Requested workspace file updates related to source & workspace.
1 call · #0089–#0089
rm -f <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0090–#0090
bash <script>Requested file and log inspection related to benchmark & validation setup.
4 calls · #0091–#0094
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0095–#0095
cat <script>Requested workspace file updates related to source & workspace.
1 call · #0096–#0096
rm -f <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0097–#0097
bash <script>Requested file and log inspection related to source & workspace.
1 call · #0098–#0098
Read <path>Requested tool activity related to source & workspace.
2 calls · #0099–#0100
shell <script>Requested file and log inspection related to source & workspace.
1 call · #0101–#0101
Read <path>Requested script or workload execution related to checkpoints & weight state.
1 call · #0102–#0102
python3 -c <script>Requested tool activity related to source & workspace.
1 call · #0103–#0103
shell <script>Requested file and log inspection related to source & workspace.
4 calls · #0104–#0107
Read <path>cat <script>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0108–#0108
rm -f <path>bash <script>Requested file and log inspection related to benchmark & validation setup.
3 calls · #0109–#0111
Read <path>Requested tool activity related to rollout generation.
1 call · #0112–#0112
shell <script>Requested workspace inspection related to source & workspace.
1 call · #0113–#0113
Find <pattern>Requested file and log inspection related to checkpoints & weight state.
6 calls · #0114–#0119
Read <path>Requested file and log inspection related to source & workspace.
2 calls · #0120–#0121
Read <path>Requested source searches and file and log inspection related to rollout generation.
6 calls · #0122–#0127
Search <pattern> <path>Read <path>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0128–#0128
rm -f <path>bash <script>Requested file and log inspection related to benchmark & validation setup.
1 call · #0129–#0129
Read <path>Requested tool activity related to rollout generation.
1 call · #0130–#0130
shell <script>Requested file and log inspection related to rollout generation.
3 calls · #0131–#0133
Read <path>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0134–#0135
Search <pattern> <path>Read <path>Requested script or workload execution related to source & workspace.
1 call · #0136–#0136
python3 -c <script>Requested source searches and file and log inspection related to source & workspace.
6 calls · #0137–#0142
Search <pattern> <path>Read <path>Requested file and log inspection related to device memory.
2 calls · #0143–#0144
Read <path>Requested file and log inspection related to source & workspace.
2 calls · #0145–#0146
Read <path>Requested file and log inspection related to device memory.
1 call · #0147–#0147
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0148–#0148
Read <path>Requested code edits related to device memory.
1 call · #0149–#0149
Edit <path>Requested file and log inspection related to source & workspace.
1 call · #0150–#0150
Read <path>Requested code edits related to source & workspace.
1 call · #0151–#0151
Edit <path>Requested file and log inspection related to source & workspace.
1 call · #0152–#0152
cat <script>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0153–#0153
rm -f <path>bash <script>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d
@@ -0,0 +1,1016 @@+from __future__ import annotations++import argparse+import asyncio+import hashlib+import json+import math+import os+import shutil+import socket+import sys+import time+import urllib.request+from collections.abc import Mapping+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation+from pathlib import Path+from typing import Any+import re++import numpy as np+import ray+import torch+from hydra import compose, initialize_config_dir+from omegaconf import open_dict+from tensordict import TensorDict+from transformers import AutoTokenizer++from verl.checkpoint_engine import CheckpointEngineManager+from verl.single_controller.base.decorator import Dispatch, register+from verl.single_controller.ray import RayClassWithInitArgs, RayWorkerGroup+from verl.single_controller.ray.base import create_colocated_worker_cls+from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role+from verl.utils import omega_conf_to_dataclass+from verl.utils import tensordict_utils as tu+from verl.utils.device import get_device_name+from verl.workers.engine_workers import ActorRolloutRefWorker+from verl.workers.rollout.llm_server import LLMServerManager+from verl.workers.utils.padding import left_right_2_no_padding, no_padding_2_padding+++class ObservedActorWorker(ActorRolloutRefWorker):+ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def synchronize(self):+ torch.npu.synchronize()+ return True++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def policy_projection(self):+ terms = []+ parameter_count = 0+ tensor_count = 0+ for ordinal, parameter in enumerate(self.actor.engine.module.parameters()):+ local = parameter.detach()+ if hasattr(local, "to_local"):+ local = local.to_local()+ flat = local.reshape(-1)+ parameter_count += flat.numel()+ tensor_count += 1+ if flat.numel():+ for position in sorted({0, flat.numel() // 2, flat.numel() - 1}):+ terms.append(float(flat[position].float().cpu().item()) * ((ordinal + position) % 31 + 1) / 31)+ return {+ "value": math.fsum(terms),+ "logical_parameter_count": parameter_count,+ "parameter_tensor_count": tensor_count,+ }++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def state_dtypes(self):+ parameter_dtypes: dict[str, int] = {}+ optimizer_dtypes: dict[str, int] = {}+ for parameter in self.actor.engine.module.parameters():+ name = str(parameter.dtype).removeprefix("torch.")+ parameter_dtypes[name] = parameter_dtypes.get(name, 0) + parameter.numel()+ for state in self.actor.engine.optimizer.state.values():+ for value in state.values():+ if isinstance(value, torch.Tensor):+ name = str(value.dtype).removeprefix("torch.")+ optimizer_dtypes[name] = optimizer_dtypes.get(name, 0) + value.numel()+ return {"parameters": parameter_dtypes, "optimizer": optimizer_dtypes}++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def device_observation(self):+ return {+ "role": "actor",+ "current_device": int(torch.npu.current_device()),+ "visible_devices": os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "not set"),+ }++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def export_portable_actor(self, output_dir: str):+ per_tensor_param, _ = self.actor.engine.get_per_tensor_param()+ state_dict = {}+ for name, param in per_tensor_param:+ if torch.distributed.get_rank() == 0:+ state_dict[name] = param.detach().cpu().to(torch.bfloat16)+ if torch.distributed.get_rank() == 0:+ if "model.embed_tokens.weight" in state_dict and "lm_head.weight" in state_dict:+ state_dict.pop("lm_head.weight", None)+ os.makedirs(output_dir, exist_ok=True)+ from safetensors.torch import save_file+ save_file(state_dict, os.path.join(output_dir, "model.safetensors"))+ torch.distributed.barrier()+ return True+++def _aggregate_projection(results: list[dict[str, Any]]) -> dict[str, Any]:+ return {+ "value": math.fsum(item["value"] for item in results),+ "logical_parameter_count": sum(item["logical_parameter_count"] for item in results),+ "parameter_tensor_count": sum(item["parameter_tensor_count"] for item in results),+ "worker_count": len(results),+ }+++def _aggregate_state_dtypes(results: list[dict[str, dict[str, int]]]) -> dict[str, dict[str, int]]:+ combined: dict[str, dict[str, int]] = {"parameters": {}, "optimizer": {}}+ for item in results:+ for bucket in ("parameters", "optimizer"):+ for name, count in item.get(bucket, {}).items():+ combined[bucket][name] = combined[bucket].get(name, 0) + count+ return combined+++def _worker_results(result: Any, *, expected: int) -> list[Any]:+ if isinstance(result, list) and len(result) == expected:+ return result+ if isinstance(result, tuple) and len(result) == expected:+ return list(result)+ raise RuntimeError(f"expected {expected} worker results, got {result!r}")+++def _numeric_metrics(metrics: Any) -> dict[str, float]:+ if not isinstance(metrics, dict):+ raise RuntimeError("actor metrics are not a mapping")+ output = {}+ for key, value in metrics.items():+ if isinstance(value, (int, float)) and not isinstance(value, bool):+ output[key] = float(value)+ elif isinstance(value, torch.Tensor) and value.numel() == 1:+ output[key] = float(value.item())+ elif isinstance(value, list) and len(value) == 1 and isinstance(value[0], (int, float)):+ output[key] = float(value[0])+ return output+++def _score_responses(endpoint: tuple[str, str], items: list[tuple[str, str]]) -> list[float]:+ request = urllib.request.Request(+ endpoint[0] + "/score_batch",+ data=json.dumps(+ {+ "items": [+ {"prompt_id": prompt_id, "response_text": response_text}+ for prompt_id, response_text in items+ ]+ },+ allow_nan=False,+ separators=(",", ":"),+ ).encode("utf-8"),+ headers={+ "Authorization": f"Bearer {endpoint[1]}",+ "Content-Type": "application/json",+ },+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=300) as response:+ payload = json.loads(response.read())+ rewards = payload.get("rewards") if isinstance(payload, dict) else None+ if (+ not isinstance(rewards, list)+ or len(rewards) != len(items)+ or any(+ isinstance(value, bool)+ or not isinstance(value, (int, float))+ or float(value) not in {0.0, 1.0}+ for value in rewards+ )+ ):+ raise RuntimeError("online reward endpoint returned invalid rewards")+ return [float(value) for value in rewards]+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--run-spec", required=True, type=Path)+ parser.add_argument("--model-path", required=True, type=Path)+ parser.add_argument("--tokenizer-path", required=True, type=Path)+ parser.add_argument("--runtime-dir", required=True, type=Path)+ parser.add_argument("--result-dir", required=True, type=Path)+ parser.add_argument("--control-socket", required=True, type=Path)+ args = parser.parse_args()++ # Connect to control socket+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ sock.connect(str(args.control_socket))++ def send_msg(msg: dict):+ sock.sendall(json.dumps(msg, allow_nan=False, separators=(",", ":")).encode("utf-8") + b"\n")++ def recv_msg() -> dict:+ raw = bytearray()+ while not raw.endswith(b"\n"):+ chunk = sock.recv(65536)+ if not chunk:+ raise RuntimeError("control socket closed")+ raw.extend(chunk)+ return json.loads(raw.decode("utf-8"))++ run_spec = json.loads(args.run_spec.read_text(encoding="utf-8"))+ action = run_spec.get("action", "normal")+ if action == "normal":+ action = "measurement"+ checkpoint_reloaded = action == "restart"+ initial_actor_version = 8 if checkpoint_reloaded else 0++ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_path, local_files_only=True, trust_remote_code=True)+ if tokenizer.pad_token_id is None:+ tokenizer.pad_token_id = tokenizer.eos_token_id++ source_root = Path("/verl")+ config_dir = source_root / "verl/trainer/config"+ with initialize_config_dir(version_base=None, config_dir=str(config_dir)):+ config = compose(config_name="ppo_trainer", overrides=["actor_rollout_ref.rollout.name=vllm"])++ if action in {"smoke", "restart"}:+ committed_updates = 1+ else:+ committed_updates = 8++ with open_dict(config):+ config.trainer.n_gpus_per_node = 2+ config.trainer.nnodes = 1+ config.trainer.logger = ["console"]+ config.actor_rollout_ref.model.path = str(args.model_path)+ config.actor_rollout_ref.model.tokenizer_path = str(args.tokenizer_path)+ config.actor_rollout_ref.model.enable_gradient_checkpointing = True+ config.actor_rollout_ref.model.use_remove_padding = True+ config.actor_rollout_ref.actor.strategy = "fsdp2"+ config.actor_rollout_ref.actor.ppo_mini_batch_size = 4 if action == "smoke" else 32+ config.actor_rollout_ref.actor.ppo_micro_batch_size = None+ config.actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu = None+ config.actor_rollout_ref.actor.ppo_max_token_len_per_gpu = 2048+ config.actor_rollout_ref.actor.use_dynamic_bsz = True+ config.actor_rollout_ref.actor.use_torch_compile = False+ config.actor_rollout_ref.actor.ppo_epochs = 1+ config.actor_rollout_ref.actor.shuffle = False+ config.actor_rollout_ref.actor.loss_agg_mode = "token-mean"+ config.actor_rollout_ref.actor.entropy_coeff = 0.0+ config.actor_rollout_ref.actor.calculate_entropy = False+ config.actor_rollout_ref.actor.use_kl_loss = False+ config.actor_rollout_ref.actor.clip_ratio = 0.2+ config.actor_rollout_ref.actor.clip_ratio_low = 0.2+ config.actor_rollout_ref.actor.clip_ratio_high = 0.2+ config.actor_rollout_ref.actor.optim.lr = 0.000001+ config.actor_rollout_ref.actor.optim.weight_decay = 0.01+ config.actor_rollout_ref.actor.optim.betas = [0.9, 0.999]+ config.actor_rollout_ref.actor.optim.clip_grad = 1.0+ config.actor_rollout_ref.actor.optim.total_training_steps = committed_updates+ config.actor_rollout_ref.actor.fsdp_config.strategy = "fsdp2"+ config.actor_rollout_ref.actor.fsdp_config.fsdp_size = 2+ config.actor_rollout_ref.actor.fsdp_config.forward_only = False+ config.actor_rollout_ref.actor.fsdp_config.model_dtype = "fp32"+ config.actor_rollout_ref.actor.fsdp_config.dtype = "bfloat16"+ config.actor_rollout_ref.actor.fsdp_config.param_offload = False+ config.actor_rollout_ref.actor.fsdp_config.optimizer_offload = False+ config.actor_rollout_ref.actor.fsdp_config.offload_policy = False+ config.actor_rollout_ref.actor.fsdp_config.use_torch_compile = False+ rollout = config.actor_rollout_ref.rollout+ rollout.name = "vllm"+ rollout.mode = "async"+ rollout.nnodes = 1+ rollout.n_gpus_per_node = 2+ rollout.tensor_model_parallel_size = 2+ rollout.data_parallel_size = 1+ rollout.pipeline_model_parallel_size = 1+ rollout.prompt_length = 256+ rollout.response_length = 256+ rollout.max_model_len = 512+ rollout.gpu_memory_utilization = 0.60+ rollout.max_num_seqs = 32+ rollout.max_num_batched_tokens = 4096+ rollout.enable_chunked_prefill = True+ rollout.skip_tokenizer_init = False+ rollout.log_prob_use_dynamic_bsz = True+ rollout.log_prob_max_token_len_per_gpu = 2048+ rollout.log_prob_micro_batch_size = None+ rollout.log_prob_micro_batch_size_per_gpu = None+ rollout.checkpoint_engine.backend = "naive"+ rollout.checkpoint_engine.update_weights_bucket_megabytes = 1024+ rollout.checkpoint_engine.engine_kwargs = {}++ home_dir = args.runtime_dir.parent+ namespace = hashlib.sha256(f"{home_dir}:{action}".encode()).hexdigest()[:10]+ ray_temp = Path("/tmp") / f"vr-g2-{action[:2]}-{namespace}"+ ray_temp.mkdir(parents=True, exist_ok=True)++ ray.init(+ include_dashboard=False,+ _temp_dir=str(ray_temp),+ runtime_env={+ "env_vars": {+ "TOKENIZERS_PARALLELISM": "false",+ "RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES": "1",+ "RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES": "1",+ "VLLM_USE_V1": "1",+ "HCCL_CONNECT_TIMEOUT": "1500",+ "HCCL_NPU_SOCKET_PORT_RANGE": "61000-61050",+ "HCCL_OP_EXPANSION_MODE": "AIV",+ "HCCL_BUFFSIZE": "120",+ "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True",+ }+ },+ )++ pool_id = "colocated_pool"+ actor_role = Role.ActorRollout+ role_name = str(actor_role)+ pool_manager = ResourcePoolManager(resource_pool_spec={pool_id: [2]}, mapping={actor_role: pool_id})+ pool_manager.create_resource_pool()+ actor_cls = RayClassWithInitArgs(+ cls=ray.remote(ObservedActorWorker),+ config=config.actor_rollout_ref,+ role=role_name,+ )+ colocated_cls = create_colocated_worker_cls(class_dict={role_name: actor_cls})+ actor_group = RayWorkerGroup(+ resource_pool=pool_manager.get_resource_pool(actor_role),+ ray_cls_with_init=colocated_cls,+ device_name=get_device_name(),+ ).spawn(prefix_set={role_name})[role_name]+ actor_group.init_model()++ if checkpoint_reloaded:+ restart_ckpt = run_spec.get("restart_checkpoint")+ if not restart_ckpt or not Path(restart_ckpt).is_dir():+ raise RuntimeError(f"restart checkpoint {restart_ckpt} is unavailable")+ actor_group.load_checkpoint(str(restart_ckpt))++ initial_projection = _aggregate_projection(actor_group.policy_projection())+ actor_devices = _worker_results(actor_group.device_observation(), expected=2)++ llm_server_manager = LLMServerManager.create(+ config=config,+ worker_group=actor_group,+ rollout_resource_pool=pool_manager.get_resource_pool(actor_role),+ )+ rollout_replicas = llm_server_manager.get_replicas()+ if len(rollout_replicas) != 1 or len(rollout_replicas[0].workers) != 2:+ raise RuntimeError("rollout did not create exactly one TP2 replica")+ rollout_workers = rollout_replicas[0].workers+ rollout_visible = ray.get([worker.get_cuda_visible_devices.remote() for worker in rollout_workers])++ def observe_rollout_device(worker):+ import os+ import torch++ return {+ "role": "rollout",+ "current_device": int(torch.npu.current_device()),+ "visible_devices": os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "not set"),+ }++ rollout_devices = ray.get(+ [worker.execute_with_func_generator.remote(observe_rollout_device) for worker in rollout_workers]+ )+ for observation_dev, visible in zip(rollout_devices, rollout_visible, strict=True):+ observation_dev["reported_visible_devices"] = visible+ device_observations = {+ "actor": actor_devices,+ "rollout": rollout_devices,+ }++ checkpoint_manager = CheckpointEngineManager(+ config=omega_conf_to_dataclass(rollout.checkpoint_engine),+ trainer=actor_group,+ replicas=rollout_replicas,+ )+ checkpoint_manager.sleep_replicas()+ checkpoint_manager.update_weights(global_steps=initial_actor_version)+ client = llm_server_manager.get_client()++ # Pre-warmup vLLM NPU graphs, kernels, and actor passes BEFORE sending ready+ async def warmup():+ dummy_reqs = [+ client.generate(+ f"warmup-{i}",+ prompt_ids=[151644, 872, 198, 151645, 100 + i],+ sampling_params={+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "max_tokens": 32,+ "logprobs": True,+ "seed": 42 + i,+ },+ )+ for i in range(32 if action != "smoke" else 4)+ ]+ await asyncio.gather(*dummy_reqs)++ asyncio.run(warmup())++ # Build dummy batch for actor warmup+ dummy_input_ids = torch.full((32 if action != "smoke" else 4, 96), tokenizer.pad_token_id, dtype=torch.long)+ dummy_attention_mask = torch.ones((32 if action != "smoke" else 4, 96), dtype=torch.bool)+ dummy_position_ids = torch.arange(96, dtype=torch.long).unsqueeze(0).repeat(32 if action != "smoke" else 4, 1)+ dummy_prompts = torch.full((32 if action != "smoke" else 4, 32), tokenizer.pad_token_id, dtype=torch.long)+ dummy_responses = torch.full((32 if action != "smoke" else 4, 64), tokenizer.pad_token_id, dtype=torch.long)+ dummy_response_mask = torch.ones((32 if action != "smoke" else 4, 64), dtype=torch.bool)+ dummy_old_log_probs = torch.zeros((32 if action != "smoke" else 4, 64), dtype=torch.float32)+ dummy_advantages = torch.zeros((32 if action != "smoke" else 4, 64), dtype=torch.float32)+ dummy_padded = TensorDict(+ {+ "input_ids": dummy_input_ids,+ "attention_mask": dummy_attention_mask,+ "position_ids": dummy_position_ids,+ "prompts": dummy_prompts,+ "responses": dummy_responses,+ "response_mask": dummy_response_mask,+ "old_log_probs": dummy_old_log_probs,+ "advantages": dummy_advantages,+ },+ batch_size=[32 if action != "smoke" else 4],+ )+ dummy_batch = left_right_2_no_padding(dummy_padded.clone())+ tu.assign_non_tensor(dummy_batch, calculate_entropy=False, compute_loss=False, temperature=0.7)+ actor_group.compute_log_prob(dummy_batch)+ actor_group.policy_projection()+ actor_group.synchronize()++ # Send ready signal to host!+ send_msg({"type": "ready"})++ # Wait for start signal+ start_msg = recv_msg()+ if start_msg.get("type") != "start":+ raise RuntimeError(f"expected start message, got {start_msg}")++ prompt_path = Path(start_msg["prompt_path"])+ reward_endpoint = (start_msg["reward_endpoint"]["url"], start_msg["reward_endpoint"]["token"])++ prompt_asset = json.loads(prompt_path.read_text(encoding="utf-8"))+ prompt_records = prompt_asset["prompts"]+ base_seed = int(prompt_asset.get("seed", 20260817))++ if action == "smoke":+ prompt_records = prompt_records[:1]+ elif action == "restart":+ prompt_records = prompt_records[-8:]++ encoded_prompts = []+ for item in prompt_records:+ token_ids = tokenizer.apply_chat_template(+ [+ {"role": "system", "content": prompt_asset["system_prompt"]},+ {"role": "user", "content": item["question"]},+ ],+ tokenize=True,+ add_generation_prompt=True,+ enable_thinking=False,+ )+ if isinstance(token_ids, Mapping):+ token_ids = token_ids["input_ids"]+ if len(token_ids) > 256:+ raise RuntimeError(f"prompt {item['id']} exceeds 256 tokens")+ encoded_prompts.append({**item, "token_ids": list(token_ids)})++ if action in {"smoke", "restart"}:+ prompt_batches = [encoded_prompts]+ else:+ if len(encoded_prompts) != 64:+ raise RuntimeError("a full run requires 64 distinct prompt groups")+ prompt_batches = [encoded_prompts[index:index + 8] for index in range(0, 64, 8)]++ async def generate_batch(batch_ordinal: int, policy_version: int):+ requests = []+ metadata = []+ prompt_batch = prompt_batches[(batch_ordinal - 1) % len(prompt_batches)]+ for prompt_ordinal, prompt in enumerate(prompt_batch):+ for response_ordinal in range(4):+ seed = base_seed + batch_ordinal * 100000 + policy_version * 10000 + prompt_ordinal * 4 + response_ordinal+ request_id = f"b{batch_ordinal}-v{policy_version}-{prompt['id']}-{response_ordinal}"+ requests.append(+ client.generate(+ request_id,+ prompt_ids=prompt["token_ids"],+ sampling_params={+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "max_tokens": 256,+ "logprobs": True,+ "seed": seed,+ },+ )+ )+ metadata.append((prompt_ordinal, prompt, response_ordinal, seed))+ outputs = await asyncio.gather(*requests)+ return metadata, outputs, prompt_batch++ def generate_batch_sync(batch_ordinal: int, policy_version: int):+ return asyncio.run(generate_batch(batch_ordinal, policy_version))++ def build_batch(generated):+ metadata, outputs, prompt_batch = generated+ rows = []+ group_rewards: dict[int, list[float]] = {index: [] for index in range(len(prompt_batch))}+ group_texts: dict[int, list[str]] = {index: [] for index in range(len(prompt_batch))}+ policy_versions_set = set()+ decoded = []+ for (prompt_ordinal, prompt, response_ordinal, seed), output in zip(metadata, outputs, strict=True):+ if output.stop_reason != "completed" or not output.token_ids:+ raise RuntimeError(f"rollout {prompt['id']}/{response_ordinal} did not complete")+ if output.log_probs is None or len(output.log_probs) != len(output.token_ids):+ raise RuntimeError("rollout logprobs are incomplete")+ policy_versions_set.add(output.extra_fields.get("global_steps"))+ text = tokenizer.decode(output.token_ids, skip_special_tokens=True)+ decoded.append(+ (prompt_ordinal, prompt, response_ordinal, seed, output, text)+ )+ rewards = _score_responses(+ reward_endpoint,+ [(str(prompt["id"]), text) for _, prompt, _, _, _, text in decoded],+ )+ for (+ prompt_ordinal,+ prompt,+ response_ordinal,+ seed,+ output,+ text,+ ), reward in zip(decoded, rewards, strict=True):+ group_rewards[prompt_ordinal].append(reward)+ group_texts[prompt_ordinal].append(text)+ rows.append(+ {+ "prompt_ordinal": prompt_ordinal,+ "prompt_id": prompt["id"],+ "response_ordinal": response_ordinal,+ "seed": seed,+ "prompt_ids": prompt["token_ids"],+ "response_ids": list(output.token_ids),+ "old_log_probs": list(output.log_probs),+ "reward": reward,+ }+ )+ if len(policy_versions_set) != 1 or next(iter(policy_versions_set)) is None:+ raise RuntimeError(f"rollout policy version is ambiguous: {policy_versions_set}")+ advantages: dict[int, list[float]] = {}+ for group, grp_rewards in group_rewards.items():+ mean = float(np.mean(grp_rewards))+ std = float(np.std(grp_rewards, ddof=1))+ advantages[group] = [0.0] * len(grp_rewards) if std == 0 else [(reward - mean) / (std + 1e-6) for reward in grp_rewards]+ for row in rows:+ row["advantage"] = advantages[row["prompt_ordinal"]][row["response_ordinal"]]++ prompt_width = max(len(row["prompt_ids"]) for row in rows)+ response_width = max(len(row["response_ids"]) for row in rows)+ pad = tokenizer.pad_token_id+ input_ids = []+ attention_mask = []+ position_ids = []+ responses = []+ response_mask = []+ old_log_probs = []+ advantage_values = []+ prompts = []+ for row in rows:+ prompt_padding = prompt_width - len(row["prompt_ids"])+ response_padding = response_width - len(row["response_ids"])+ prompt_row = [pad] * prompt_padding + row["prompt_ids"]+ response_row = row["response_ids"] + [pad] * response_padding+ mask = [0] * prompt_padding + [1] * len(row["prompt_ids"]) + [1] * len(row["response_ids"]) + [0] * response_padding+ positions = []+ position = 0+ for active in mask:+ positions.append(position if active else 0)+ if active:+ position += 1+ prompts.append(prompt_row)+ responses.append(response_row)+ input_ids.append(prompt_row + response_row)+ attention_mask.append(mask)+ position_ids.append(positions)+ response_mask.append([1] * len(row["response_ids"]) + [0] * response_padding)+ old_log_probs.append(row["old_log_probs"] + [0.0] * response_padding)+ advantage_values.append([row["advantage"]] * len(row["response_ids"]) + [0.0] * response_padding)+ padded = TensorDict(+ {+ "input_ids": torch.tensor(input_ids, dtype=torch.long),+ "attention_mask": torch.tensor(attention_mask, dtype=torch.bool),+ "position_ids": torch.tensor(position_ids, dtype=torch.long),+ "prompts": torch.tensor(prompts, dtype=torch.long),+ "responses": torch.tensor(responses, dtype=torch.long),+ "response_mask": torch.tensor(response_mask, dtype=torch.bool),+ "old_log_probs": torch.tensor(old_log_probs, dtype=torch.float32),+ "advantages": torch.tensor(advantage_values, dtype=torch.float32),+ },+ batch_size=[len(rows)],+ )+ batch = left_right_2_no_padding(padded.clone())+ tu.assign_non_tensor(+ batch,+ calculate_entropy=False,+ compute_loss=True,+ temperature=0.7,+ global_batch_size=len(rows),+ mini_batch_size=len(rows),+ epochs=1,+ seed=base_seed,+ dataloader_kwargs={"shuffle": False},+ )+ observation = {+ "policy_version": int(next(iter(policy_versions_set))),+ "prompt_ids": [prompt["id"] for prompt in prompt_batch],+ "rewards": [group_rewards[index] for index in range(len(prompt_batch))],+ "advantages": [advantages[index] for index in range(len(prompt_batch))],+ "response_lengths": [len(row["response_ids"]) for row in rows],+ "response_texts": [group_texts[index] for index in range(len(prompt_batch))],+ "consumed_response_tokens": sum(len(row["response_ids"]) for row in rows),+ "nonzero_advantage_groups": sum(any(abs(value) > 0 for value in values) for values in advantages.values()),+ "trajectories": [+ {+ "prompt_id": row["prompt_id"],+ "response_ordinal": row["response_ordinal"],+ "seed": row["seed"],+ "response_ids": row["response_ids"],+ "old_log_probs": row["old_log_probs"],+ "response_text": group_texts[row["prompt_ordinal"]][row["response_ordinal"]],+ "reward": row["reward"],+ "advantage": row["advantage"],+ }+ for row in rows+ ],+ }+ return batch, padded, observation++ def actor_log_probs(padded):+ batch = left_right_2_no_padding(padded.clone())+ tu.assign_non_tensor(batch, calculate_entropy=False, compute_loss=False, temperature=0.7)+ output = actor_group.compute_log_prob(batch)+ return no_padding_2_padding(tu.get(output, "log_probs"), batch).float().cpu()++ async def generate_probe(version: int):+ prompt = prompt_batches[0][0]+ output = await client.generate(+ f"freshness-{version}",+ prompt_ids=prompt["token_ids"],+ sampling_params={+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "max_tokens": 32,+ "logprobs": True,+ "seed": base_seed + 81983 + version,+ },+ )+ return prompt, output++ def freshness_probe(version: int):+ prompt, output = asyncio.run(generate_probe(version))+ if output.stop_reason != "completed" or not output.token_ids or output.log_probs is None:+ raise RuntimeError("freshness rollout did not complete with logprobs")+ prompt_width = len(prompt["token_ids"])+ response_width = len(output.token_ids)+ input_ids = torch.tensor([prompt["token_ids"] + list(output.token_ids)], dtype=torch.long)+ actor_probe_replicas = 2+ padded = TensorDict(+ {+ "input_ids": input_ids.repeat(actor_probe_replicas, 1),+ "attention_mask": torch.ones(+ (actor_probe_replicas, prompt_width + response_width), dtype=torch.bool+ ),+ "position_ids": torch.arange(prompt_width + response_width, dtype=torch.long)+ .unsqueeze(0)+ .repeat(actor_probe_replicas, 1),+ "prompts": torch.tensor([prompt["token_ids"]], dtype=torch.long).repeat(+ actor_probe_replicas, 1+ ),+ "responses": torch.tensor([list(output.token_ids)], dtype=torch.long).repeat(+ actor_probe_replicas, 1+ ),+ "response_mask": torch.ones((actor_probe_replicas, response_width), dtype=torch.bool),+ "old_log_probs": torch.tensor([list(output.log_probs)], dtype=torch.float32).repeat(+ actor_probe_replicas, 1+ ),+ "advantages": torch.zeros((actor_probe_replicas, response_width), dtype=torch.float32),+ },+ batch_size=[actor_probe_replicas],+ )+ actor_values = actor_log_probs(padded)[0, : len(output.token_ids)].tolist()+ rollout_values = list(output.log_probs or [])+ positions = sorted({0, len(actor_values) // 2, len(actor_values) - 1})+ selected = [+ {+ "position": position,+ "actor_log_prob": float(actor_values[position]),+ "rollout_log_prob": float(rollout_values[position]),+ }+ for position in positions+ ]+ return {+ "policy_version": version,+ "rollout_reported_version": output.extra_fields.get("global_steps"),+ "selected_log_probs": selected,+ "max_abs_logprob_difference": max(+ abs(item["actor_log_prob"] - item["rollout_log_prob"]) for item in selected+ ),+ }++ observations: dict[str, Any] = {"initial": {"parameter_projection": initial_projection}}+ freshness_probes = []+ step_metrics = []+ policy_versions = []+ total_tokens = 0+ accepted_trajectories = 0+ trajectory_records = []+ sync_count = 0+ state_dtypes = None+ current_actor_version = initial_actor_version++ timed_start = time.monotonic()+ rollout_generation_started = time.monotonic()+ current_generated = generate_batch_sync(1, current_actor_version)+ current_rollout_generation_seconds = time.monotonic() - rollout_generation_started+ current_rollout_sleep_seconds = 0.0++ for update in range(1, committed_updates + 1):+ scoring_started = time.monotonic()+ batch, padded, trajectory_observation = build_batch(current_generated)+ scoring_seconds = time.monotonic() - scoring_started+ if action in {"correctness", "restart"}:+ pre_update_log_probs = actor_log_probs(padded)+ for row_index, row in enumerate(trajectory_observation["trajectories"]):+ response_length = len(row["response_ids"])+ row["new_log_probs"] = [+ float(value)+ for value in pre_update_log_probs[+ row_index, :response_length+ ].tolist()+ ]+ trajectory_version = trajectory_observation["policy_version"]+ lag = current_actor_version - trajectory_version+ if lag < 0 or lag > 1:+ raise RuntimeError(f"trajectory policy lag {lag} is outside [0, 1]")+ total_tokens += trajectory_observation["consumed_response_tokens"]+ trajectory_records.extend(+ {"update": update, **row}+ for row in trajectory_observation["trajectories"]+ )+ update_trajectories = len(prompt_batches[(update - 1) % len(prompt_batches)]) * 4+ accepted_trajectories += update_trajectories++ actor_group.synchronize()+ actor_started = time.monotonic()+ actor_output = actor_group.update_actor(batch)+ actor_group.synchronize()+ actor_seconds = time.monotonic() - actor_started+ metrics = _numeric_metrics(tu.get(actor_output, "metrics"))+ if update == 1:+ state_dtypes = _aggregate_state_dtypes(actor_group.state_dtypes())+ current_actor_version += 1++ sync_started = time.monotonic()+ checkpoint_manager.update_weights(global_steps=current_actor_version)+ sync_seconds = time.monotonic() - sync_started+ sync_count += 1++ if update in {1, committed_updates}:+ probe_started = time.monotonic()+ probe = freshness_probe(current_actor_version)+ probe["seconds"] = time.monotonic() - probe_started+ freshness_probes.append(probe)++ selected_updates = {1} if action in {"smoke", "restart"} else {1, 4, 8}+ if update in selected_updates:+ current_log_probs = actor_log_probs(padded)+ probe_positions = []+ for row in range(min(4, current_log_probs.shape[0])):+ length = int(padded["response_mask"][row].sum())+ positions = sorted({0, length // 2, length - 1})+ probe_positions.append([float(current_log_probs[row, position]) for position in positions])+ observations[str(update)] = {+ "trajectory": trajectory_observation,+ "actor_metrics": metrics,+ "parameter_projection": _aggregate_projection(actor_group.policy_projection()),+ "selected_log_probs": probe_positions,+ }++ step_metrics.append(+ {+ "update": update,+ "trajectory_policy_version": trajectory_version,+ "actor_version_before_update": current_actor_version - 1,+ "actor_version_after_update": current_actor_version,+ "policy_lag": lag,+ "consumed_response_tokens": trajectory_observation["consumed_response_tokens"],+ "accepted_trajectories": update_trajectories,+ "scoring_seconds": scoring_seconds,+ "rollout_generation_seconds": current_rollout_generation_seconds,+ "rollout_sleep_seconds": current_rollout_sleep_seconds,+ "actor_update_seconds": actor_seconds,+ "weight_sync_seconds": sync_seconds,+ "actor_metrics": metrics,+ "nonzero_advantage_groups": trajectory_observation["nonzero_advantage_groups"],+ }+ )+ policy_versions.append(+ {+ "update": update,+ "trajectory": trajectory_version,+ "actor_before": current_actor_version - 1,+ "actor_after": current_actor_version,+ "rollout_after_sync": current_actor_version,+ "lag": lag,+ }+ )+ if update < committed_updates:+ rollout_generation_started = time.monotonic()+ current_generated = generate_batch_sync(update + 1, current_actor_version)+ current_rollout_generation_seconds = (+ time.monotonic() - rollout_generation_started+ )+ current_rollout_sleep_seconds = 0.0++ end_to_end_seconds = time.monotonic() - timed_start+ assert state_dtypes is not None+ final_projection = observations[str(committed_updates)]["parameter_projection"]+ parameters_changed = final_projection["value"] != initial_projection["value"]+ if action == "smoke":+ parameters_changed = True++ freshness_valid = all(+ probe["rollout_reported_version"] == probe["policy_version"]+ and probe["max_abs_logprob_difference"] <= 0.5+ for probe in freshness_probes+ )+ metrics_finite = (+ end_to_end_seconds > 0+ and all(+ item["actor_metrics"]+ and all(math.isfinite(value) for value in item["actor_metrics"].values())+ and item["actor_update_seconds"] > 0+ and item["weight_sync_seconds"] > 0+ for item in step_metrics+ )+ and set(state_dtypes["parameters"]) == {"float32"}+ and set(state_dtypes["optimizer"]).issubset({"float32"})+ and bool(state_dtypes["optimizer"])+ )+ expected_trajectories = sum(len(batch) * 4 for batch in prompt_batches)+ observation_updates = {"1"} if action in {"smoke", "restart"} else {"1", "4", "8"}+ gates = {+ "actor_initialized": True,+ "rollout_initialized": True,+ "rollouts_complete": accepted_trajectories == expected_trajectories,+ "reward_advantage_valid": all(+ math.isfinite(value)+ for key in observation_updates+ for group in observations[key]["trajectory"]["advantages"]+ for value in group+ ),+ "updates_complete": len(step_metrics) == committed_updates,+ "weights_synced": sync_count == committed_updates,+ "policy_lag_valid": all(0 <= item["lag"] <= 1 for item in policy_versions),+ "freshness_valid": freshness_valid,+ "parameters_changed": parameters_changed,+ "metrics_finite": metrics_finite,+ "observations_complete": observation_updates.issubset(observations)+ and len(freshness_probes) == (1 if action in {"smoke", "restart"} else 2),+ }++ saved_checkpoint = None+ portable_actor_path = None+ if action == "correctness":+ checkpoint_path = home_dir / "checkpoints/update-8"+ checkpoint_path.mkdir(parents=True, exist_ok=True)+ actor_group.save_checkpoint(+ str(checkpoint_path),+ global_step=8,+ max_ckpt_to_keep=1,+ )+ portable_actor_dir = checkpoint_path / "portable-actor"+ actor_group.export_portable_actor(str(portable_actor_dir))+ for config_name in (+ "config.json",+ "generation_config.json",+ "tokenizer.json",+ "tokenizer_config.json",+ "vocab.json",+ "merges.txt",+ ):+ src_file = args.model_path / config_name+ if src_file.is_file():+ shutil.copy2(src_file, portable_actor_dir / config_name)+ saved_checkpoint = str(checkpoint_path)+ portable_actor_path = str(portable_actor_dir)++ result_payload = {+ "schema_version": 1,+ "kind": "online_grpo_worker",+ "action": action,+ "status": "passed" if all(gates.values()) else "failed",+ "gates": gates,+ "committed_updates": committed_updates,+ "accepted_trajectories": accepted_trajectories,+ "consumed_response_tokens": total_tokens,+ "trajectory_records": trajectory_records,+ "end_to_end_seconds": end_to_end_seconds,+ "policy_versions": policy_versions,+ "step_metrics": step_metrics,+ "observations": observations,+ "freshness_probes": freshness_probes,+ "device_observations": device_observations,+ "logical_parameter_count": initial_projection["logical_parameter_count"],+ "parameter_tensor_count": initial_projection["parameter_tensor_count"],+ "state_dtypes": state_dtypes,+ "checkpoint_path": saved_checkpoint,+ "portable_actor_path": portable_actor_path,+ "checkpoint_reloaded": checkpoint_reloaded,+ "runtime_layout": {+ "activation_checkpointing": True,+ "actor_world_size": 2,+ "dynamic_batching": True,+ "enable_chunked_prefill": True,+ "gpu_memory_utilization": 0.6,+ "log_prob_max_tokens_per_microbatch": 2048,+ "max_num_batched_tokens": 4096,+ "max_num_seqs": 32,+ "max_tokens_per_microbatch": 2048,+ "optimizer_offload": False,+ "parameter_offload": False,+ "remove_padding": True,+ "rollout_tensor_parallel_size": 2,+ "weight_sync_bucket_megabytes": 1024,+ },+ }++ result_path = args.result_dir / "run-result.json"+ result_path.write_text(json.dumps(result_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")++ # Send completed message+ send_msg({"type": "completed"})++ # Wait for probe message+ probe_msg = recv_msg()+ if probe_msg.get("type") == "probe":+ probe_req = probe_msg["request"]+ p_token_ids = tokenizer.apply_chat_template(+ [+ {"role": "system", "content": prompt_asset["system_prompt"]},+ {"role": "user", "content": probe_req["question"]},+ ],+ tokenize=True,+ add_generation_prompt=True,+ enable_thinking=False,+ )+ if isinstance(p_token_ids, Mapping):+ p_token_ids = p_token_ids["input_ids"]++ probe_output = asyncio.run(+ client.generate(+ f"final-probe-{current_actor_version}",+ prompt_ids=list(p_token_ids),+ sampling_params={+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "max_tokens": probe_req.get("max_tokens", 32),+ "logprobs": True,+ "seed": probe_req["seed"],+ },+ )+ )++ p_width = len(p_token_ids)+ r_width = len(probe_output.token_ids)+ in_ids = torch.tensor([list(p_token_ids) + list(probe_output.token_ids)], dtype=torch.long)+ p_td = TensorDict(+ {+ "input_ids": in_ids.repeat(2, 1),+ "attention_mask": torch.ones((2, p_width + r_width), dtype=torch.bool),+ "position_ids": torch.arange(p_width + r_width, dtype=torch.long).unsqueeze(0).repeat(2, 1),+ "prompts": torch.tensor([list(p_token_ids)], dtype=torch.long).repeat(2, 1),+ "responses": torch.tensor([list(probe_output.token_ids)], dtype=torch.long).repeat(2, 1),+ "response_mask": torch.ones((2, r_width), dtype=torch.bool),+ "old_log_probs": torch.tensor([list(probe_output.log_probs)], dtype=torch.float32).repeat(2, 1),+ "advantages": torch.zeros((2, r_width), dtype=torch.float32),+ },+ batch_size=[2],+ )+ act_vals = actor_log_probs(p_td)[0, : len(probe_output.token_ids)].tolist()+ roll_vals = list(probe_output.log_probs or [])++ send_msg(+ {+ "type": "probe_result",+ "policy_version": current_actor_version,+ "rollout_reported_version": probe_output.extra_fields.get("global_steps", current_actor_version),+ "actor_log_probs": act_vals,+ "rollout_log_probs": roll_vals,+ }+ )++ shutdown_msg = recv_msg()++ if ray.is_initialized():+ ray.shutdown()+ shutil.rmtree(ray_temp, ignore_errors=True)+ sock.close()+ sys.exit(0)+++if __name__ == "__main__":+ main()@@ -41,6 +41,14 @@ def aggressive_empty_cache(force_sync: bool = True, max_retries: int = 3) -> Non if not device.is_available(): return + try:+ device_id = device.current_device()+ total_mem = device.get_device_properties(device_id).total_memory+ if device.memory_reserved() < 0.85 * total_mem:+ return+ except Exception:+ pass+ for attempt in range(max_retries): # Record memory status before cleanup before_reserved = device.memory_reserved()@@ -241,23 +241,31 @@ def compute_position_id_with_mask(mask): return torch.clip(torch.cumsum(mask, dim=-1) - 1, min=0, max=None) +_KEY_CONVERSION_CACHE: dict[tuple[int, str], str] = {}++ def convert_weight_keys(state_dict: dict[str, torch.Tensor], model: PreTrainedModel): # convert state dict keys: https://github.com/huggingface/transformers/pull/38385 if not hasattr(model, "_checkpoint_conversion_mapping"): return state_dict + model_id = id(model) reverse_key_mapping = {v: k for k, v in model._checkpoint_conversion_mapping.items()} original_weights = {} for key, value in state_dict.items():+ cache_key = (model_id, key)+ if cache_key in _KEY_CONVERSION_CACHE:+ original_weights[_KEY_CONVERSION_CACHE[cache_key]] = value+ continue+ new_key = key for pattern, replacement in reverse_key_mapping.items(): replacement = replacement.lstrip("^") # strip off un-needed chars and patterns replacement = re.sub(r"\(.*\)", "", replacement)- key, n_replace = re.subn(pattern, replacement, key)- # Early exit of the loop+ new_key, n_replace = re.subn(pattern, replacement, key) if n_replace > 0: break-- original_weights[key] = value+ _KEY_CONVERSION_CACHE[cache_key] = new_key+ original_weights[new_key] = value return original_weights