text stringlengths 0 131 |
|---|
#!/usr/bin/env python3 |
"""Full-language-backbone native LLaVA RM/CM training, DeepSpeed ZeRO-2. |
Uses published optimizer settings and native score architecture/loss. Dataset |
size/provenance are explicit; this is not the author's recovered experiment. |
No LoRA, RL or judge. Launch with explicit idle physical GPUs. |
""" |
import argparse |
import gc |
import hashlib |
import json |
import math |
import os |
from pathlib import Path |
import random |
import subprocess |
import sys |
import time |
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) |
import deepspeed |
from deepspeed.ops.adam import FusedAdam |
import numpy as np |
import pyarrow.parquet as pq |
import torch |
import torch.distributed as dist |
import transformers |
from transformers import AutoProcessor, CLIPVisionConfig, LlamaConfig, LlavaConfig, get_scheduler |
from safe_rlhf_v.models.llava import AccustomedLlavaRewardModel |
from safe_rlhf_v.utils.preference_training import ( |
binary_cost_diagnostics, image_from_value, preference_loss, preference_score_diagnostics, |
ranking_diagnostics, response_text, |
) |
from safe_rlhf_v.utils.preference_distributed import ( |
configure_full_score_training, score_deepspeed_config, restore_llama_rope_fp32, |
) |
from safe_rlhf_v.utils.processors import configure_llava_processor |
from train_preference_smoke import load_base, WEIGHT_HASHES |
def main(): |
p = argparse.ArgumentParser() |
p.add_argument('--root', type=Path, required=True) |
p.add_argument('--run-name', required=True) |
p.add_argument('--dataset-name', required=True) |
p.add_argument('--kind', choices=('rm', 'cm'), required=True) |
p.add_argument('--epochs', type=int, default=3) |
p.add_argument('--batch-pairs', type=int, default=4) |
p.add_argument('--seed', type=int, default=42) |
p.add_argument('--tiny', action='store_true', help='Random small architecture engine test, not 7B training') |
p.add_argument('--limit-train', type=int) |
p.add_argument('--limit-validation', type=int) |
p.add_argument('--checkpoint-interval', type=int, default=0, |
help='Save additional optimizer snapshots every N updates; 0 disables') |
p.add_argument('--epoch-checkpoints', action='store_true') |
p.add_argument('--native-loss-precision', action='store_true', |
help='Use upstream integer-sign CM arithmetic; historical default used FP32 absolute terms') |
args = p.parse_args() |
rank, local, world = (int(os.environ[k]) for k in ('RANK', 'LOCAL_RANK', 'WORLD_SIZE')) |
devices = os.environ.get('CUDA_VISIBLE_DEVICES', '').split(',') |
if len(devices) != world or not all(s.isdigit() for s in devices) or len(set(devices)) != world: |
p.error('CUDA_VISIBLE_DEVICES must explicitly list distinct physical GPUs, one per rank') |
if min(args.epochs, args.batch_pairs) < 1 or args.checkpoint_interval < 0 or any( |
v is not None and v < world for v in (args.limit_train, args.limit_validation)): |
p.error('Invalid epochs/batch/sample limits') |
if transformers.__version__ != '4.48.3' or deepspeed.__version__ != '0.16.2': |
raise RuntimeError('Preflight is pinned to Transformers 4.48.3 / DeepSpeed 0.16.2') |
root = args.root.resolve() |
run = root / 'runs' / args.run_name / args.kind |
base, data = root / 'models/base', root / 'datasets' / args.dataset_name |
launcher_id = os.environ['TORCHELASTIC_RUN_ID'] |
if rank == 0: |
if run.exists(): |
raise RuntimeError('Run already exists; never overwrite/mix settings') |
used = subprocess.check_output(['nvidia-smi', '--id=' + ','.join(devices), |
'--query-gpu=memory.used', '--format=csv,noheader,nounits'], text=True) |
if any(int(v) > 100 for v in used.split()): |
raise RuntimeError('Selected GPU occupied; refusing to start') |
if not args.tiny: |
for index, digest in enumerate(WEIGHT_HASHES, 1): |
with (base / f'model-{index:05d}-of-00003.safetensors').open('rb') as handle: |
if hashlib.file_digest(handle, 'sha256').hexdigest() != digest: |
raise RuntimeError('Base checksum mismatch') |
run.mkdir(parents=True) |
temporary_marker = run / 'preflight-ready.tmp' |
temporary_marker.write_text(launcher_id) |
temporary_marker.replace(run / 'preflight-ready') |
else: |
deadline = time.monotonic() + 240 |
while True: |
marker = run / 'preflight-ready' |
if marker.exists() and marker.read_text() == launcher_id: |
break |
if marker.exists() and marker.read_text(): |
raise RuntimeError('Existing run belongs to a different launcher; refusing reuse') |
if time.monotonic() > deadline: |
raise RuntimeError('Rank zero preflight did not finish') |
time.sleep(0.25) |
if not (data / 'READY').exists(): |
raise RuntimeError('Dataset not ready') |
RM epoch3 final native checkpoint rescue
Final step5589 native state: 94540164632 original bytes in five originalfiles (one native model/client-state file and four ZeRO2 optimizer partitions). This is not a new inference-weight release; the matching HF score export is already pinned under pinned_export_reference. The native format preserves its own parameter precision, optimizer moments/masters, scheduler and saved RNG/client cursor data needed beyond inference weights.
Completeness and limits
Only the final checkpoint is archived, not earlier epochs or all historical training. The source records dp_world_size4/mp_world_size1, DeepSpeed0.16.2, globalsteps5589, and terminal next-epoch4/cursor0. Scheduler and rank-RNG container names were inspected statically. No pickle was executed and no new full GPU numerical exact-resume test was run. Reference trainer source explicitly captures per-rank Python/NumPy/TorchCPU/TorchCUDA RNG plus customepoch/next_local_batch_offset; data_sampler=None does not mean those customcursor fields are absent. A caller must restore the appropriate client RNG/cursor, not only invoke an optimizer load.
This role is a separately trained preference scorer, not an entire policy/actor/rewardcritic/costcritic PPO run. Nativeweights are not licensed anew by this archive; originalLlama2 license/use policy and sourcecode licenses/notices are retained. Research preservation does not certify safety or newbenchmark quality.
Recover bytes
Download this dataset at the fixed final revision from its publication receipt using hf download wangzyuan/SafeRLHFV-RM-Epoch3-Native-Checkpoint-Rescue --repo-type dataset --revision COMMIT --local-dir ./native-state. Run python ./native-state/restore_research_data.py ./native-state to verify everypart and reconstructed sourcefile before any training load. The script neverunpickles. All fivefiles must complete: partialuploads have per-file recovery manifests, but a complete role is not claimed until DATA_PARTS.json and all expectedparts/supportfiles are committed/verified.
Allow roughly twice this role's payload for a local download+reconstruction (parts plus restored originals), plus training scratch. Publisherstaging uses only onecopy of each64MiBpart; it does not keep a second originalfile copy. All sources and preparedparts remain intact.
Use the original trustedframework/runtime and explicit checkpointtag step-5589 in a four-rank environment after reviewing NATIVE_DEPENDENCIES. Frozenreference source is stored as inert .py.txt and also available at the pinned Epoch3-Reproduction revision. It includes training/restoreprobe logic and must not be executed as a blind resume command. Terminal cosine LR may bezero; extending the experiment requires an explicit newtraining plan.
Original datasetSHA bindings are preserved. Public reviewedtrain has eight isolatedrows and differentParquetserialization; it is NOT byte-identical to the original boundfile. Exactsource selection/upstream hashes and transformation references are preserved separately, but full originaldata reconstruction/environment and trajectory continuity are not certified. Payload verification uses committedfixedrevisionLFS SHA256/size; supporting files are actually anonymouslydownloaded. A new full94GB checkpointdownload/restore is not claimed.
- Downloads last month
- 407