CoolFace
Apppublic

b4rty/torchdebug-env

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
App README

๐Ÿ”ฅ TorchDebug โ€” PyTorch Training Run Debugger

An OpenEnv environment that challenges AI agents to diagnose and fix real-world PyTorch training failures.

![OpenEnv](https://github.com/meta-pytorch/OpenEnv) ![PyTorch](https://pytorch.org) ![License](LICENSE)

๐ŸŽฏ What is TorchDebug?

TorchDebug simulates the real work of an ML engineer debugging broken training runs. A training run is presented with:

  • โ€”๐Ÿ“Š Training logs showing loss/accuracy/gradient progression
  • โ€”๐Ÿ’ป Code snippets containing one or more bugs
  • โ€”โš™๏ธ Configuration detailing hyperparameters and setup
  • โ€”โŒ Error messages (if the run crashed)

The agent must investigate (analyze logs, inspect gradients, check architecture), diagnose the root cause, and prescribe a fix. Performance is graded on diagnosis accuracy, fix quality, investigation efficiency, and hint usage.

๐Ÿ—๏ธ Architecture

Reference-inspired layout (aligned with strong OpenEnv environments such as calendar/reasoning_gym/repl/tbench2):

torchdebug_env/
โ”œโ”€โ”€ ARCHITECTURE.md       # Design and layering notes
โ”œโ”€โ”€ openenv.yaml          # OpenEnv manifest
โ”œโ”€โ”€ pyproject.toml         # Dependencies
โ”œโ”€โ”€ models.py              # Pydantic Action/Observation/State models
โ”œโ”€โ”€ client.py              # Typed EnvClient wrapper
โ”œโ”€โ”€ inference.py           # Baseline LLM agent script
โ”œโ”€โ”€ __init__.py
โ”œโ”€โ”€ server/
โ”‚   โ”œโ”€โ”€ app.py             # FastAPI server entry point
โ”‚   โ”œโ”€โ”€ torchdebug_environment.py  # Core Environment implementation
โ”‚   โ””โ”€โ”€ Dockerfile         # Container build
โ”œโ”€โ”€ scenarios/
โ”‚   โ”œโ”€โ”€ __init__.py        # Scenario registry
โ”‚   โ”œโ”€โ”€ basic_failures.py  # Task 1: Easy scenarios
โ”‚   โ”œโ”€โ”€ performance_issues.py  # Task 2: Medium scenarios
โ”‚   โ””โ”€โ”€ subtle_bugs.py     # Task 3: Hard scenarios
โ””โ”€โ”€ utils/
    โ””โ”€โ”€ reward.py          # Grading & reward computation

๐Ÿ“‹ Tasks & Scenarios

Task 1: Basic Failures (Easy) โ€” 5 Scenarios

IDBugSymptom
easy_lr_too_highLearning rate 10.0 for SGDLoss explodes to NaN
easy_device_mismatchMissing model.to(device)RuntimeError: different devices
easy_wrong_lossMSELoss for classificationAccuracy stuck at ~10%
easy_missing_zero_gradNo optimizer.zero_grad()Unstable oscillating loss
easy_double_softmaxSoftmax + CrossEntropyLossAccuracy plateaus at 65%

Task 2: Performance Issues (Medium) โ€” 5 Scenarios

IDBugSymptom
med_data_leakageTrain/val data leakage99% val but 62% test accuracy
med_batchnorm_evalBatchNorm in eval during trainingModel barely learns
med_memory_leakStoring loss tensor (not .item())GPU OOM after few epochs
med_class_imbalanceNo compensation for 200:1 imbalance99.5% accuracy, 2% minority recall
med_vanishing_gradients50-layer Sigmoid MLP, no skip connectionsNear-zero gradients in early layers

Task 3: Subtle & Compound Bugs (Hard) โ€” 5 Scenarios

IDBugSymptom
hard_ddp_grad_accumDDP syncs on every backward + unscaled LR3x slower than expected
hard_mixed_precision_instabilityfp16 custom loss + tiny smoothing constantIntermittent NaN every ~200 batches
hard_weight_loading_frozenUnfrozen embeddings + weight decay on biasFine-tuning plateaus at 45%
hard_tokenizer_mismatchCased tokenizer + uncased model + no attention maskPerformance gap (76% vs 92%)
hard_fsdp_checkpointFSDP fp16 reduce + wrong clip methodIntermittent loss spikes

๐Ÿค– Agent Interface

Available Actions

ActionDescriptionWhen to Use
analyze_logsAnalyze training log patternsFirst step โ€” understand the trajectory
inspect_gradientsDeep gradient flow analysisWhen suspecting gradient issues
inspect_data_pipelineCheck data loading & splittingWhen data issues suspected
inspect_model_architectureExamine model, loss, layersWhen architecture bugs suspected
check_device_placementAnalyze tensor device placementWhen device errors occur
diagnoseSubmit root cause diagnosisAfter investigation
prescribe_fixSubmit fix (description + code)Final action โ€” ends episode
request_hintGet a progressive hintUse sparingly (score penalty)

Reward Structure

ComponentWeightDescription
Diagnosis quality40%Fuzzy keyword match against ground truth
Fix quality40%Match against correct fix description/code
Investigation efficiency10%Using relevant inspections
Step efficiency10%Fewer steps = higher bonus
Hint penalty-5/10/15%Increasing penalty per hint

๐Ÿš€ Quick Start

1. Start the Environment Server

bash
# Install dependencies
pip install -e .

# Run locally
uvicorn server.app:app --host 0.0.0.0 --port 8000

# Or with Docker
docker build -f server/Dockerfile -t torchdebug-env .
docker run -p 8000:8000 torchdebug-env

2. Run Baseline Inference

bash
# Required variables
export API_BASE_URL="https://api.openai.com/v1"
export MODEL_NAME="gpt-4"
export HF_TOKEN="sk-..."
python inference.py

# With HuggingFace Inference
export API_BASE_URL="https://api-inference.huggingface.co/v1"
export MODEL_NAME="meta-llama/Llama-3.3-70B-Instruct"
export HF_TOKEN="hf_..."
python inference.py

The baseline evaluates one deterministic scenario from each task (easy/medium/hard) and writes reproducible scores to outputs/evals/baseline_results.json.

3. Validate

bash
openenv validate torchdebug_env

4. Run Pre-submission Checks (Recommended)

bash
# Core checks (validate + local reset/step smoke tests)
python presubmit.py

# Core + deterministic grader tests are run by default
# Use --skip-tests only if your environment cannot run pytest
python presubmit.py --skip-tests

# Include container checks (docker build/run + /health + /reset)
python presubmit.py --docker

# Include baseline run (requires API_BASE_URL, MODEL_NAME, HF_TOKEN)
python presubmit.py --docker --baseline

For HF Space style external validation, use scripts/validate-submission.sh.

presubmit.py now also writes a machine-readable report to outputs/evals/submission_report.json.

๐Ÿ“Š Baseline Results

TaskDifficultyGPT-4 Avg ScoreLlama-3-70B Avg Score
basic_failuresEasy~0.80~0.65
performance_issuesMedium~0.60~0.45
subtle_bugsHard~0.35~0.20

๐Ÿ”ง Development

bash
# Clone and install
git clone <repo-url>
cd torchdebug_env
pip install -e ".[dev]"

# Run tests
pytest tests/ -v

# Build Docker
openenv build torchdebug_env

๐ŸŒ HuggingFace Space Deployment

bash
# Deploy to HuggingFace Spaces
openenv deploy torchdebug_env --space your-username/torchdebug-env

๐Ÿ“œ License

BSD-3-Clause โ€” Compatible with Meta/PyTorch licensing.

๐Ÿ† Hackathon Context

Built for the Meta PyTorch OpenEnv Hackathon ร— Scaler School (Round 1).

Why TorchDebug matters:

  • โ€”๐Ÿ”ฅ Real-world utility: Every ML engineer spends hours debugging training runs
  • โ€”๐ŸŽฏ Sponsor alignment: Showcases PyTorch ecosystem deeply (DDP, FSDP, AMP, transformers)
  • โ€”๐Ÿง  Progressive difficulty: Tests both basic knowledge and advanced distributed training skills
  • โ€”๐Ÿ“ˆ Meaningful rewards: Partial credit for investigation โ€” not just binary pass/fail

๐Ÿงช Judging Criteria Mapping (Round 1)

1) Real-world utility (30%)

  • โ€”Environment models a real ML engineering workflow: diagnosing failed/underperforming PyTorch training jobs.
  • โ€”Scenarios include production-like issues: device mismatch, data leakage, AMP instability, DDP/FSDP interactions.

2) Task & grader quality (25%)

  • โ€”3 difficulty tiers (easy โ†’ medium โ†’ hard) with deterministic scenario definitions.
  • โ€”Programmatic scoring in utils/reward.py returns bounded scores in $[0,1]$.
  • โ€”Grader includes anti-gaming logic and evidence-alignment incentives.

3) Environment design (20%)

  • โ€”Clean episode lifecycle via reset() / step() / state() patterns.
  • โ€”Typed action/observation/state models in models.py.
  • โ€”Reward shaping includes partial progress, efficiency terms, and hint penalties.

4) Code quality & OpenEnv compliance (15%)

  • โ€”OpenEnv manifest in openenv.yaml.
  • โ€”Local validation and smoke-check automation in presubmit.py.
  • โ€”External submission validator in scripts/validate-submission.sh.
  • โ€”Dockerized runtime via server/Dockerfile.

5) Creativity & novelty (10%)

  • โ€”Focuses on training-debug intelligence rather than benchmark gaming.
  • โ€”Hard tasks require multi-factor reasoning (numerics + systems + architecture).

๐Ÿš€ Final Submission Tips (High Impact)

  • โ€”Use a hard scenario baseline in inference.py output to demonstrate non-trivial agent capability.
  • โ€”Include the generated artifacts:
  • โ€”outputs/evals/baseline_results.json
  • โ€”outputs/evals/submission_report.json
  • โ€”Before submitting HF URL, run:
  • โ€”python presubmit.py --docker --baseline
  • โ€”bash scripts/validate-submission.sh https://<your-space>.hf.space .

โœ… Submission Checklist (Practical)

  • โ€”[ ] openenv validate . passes
  • โ€”[ ] python presubmit.py --docker passes
  • โ€”[ ] python presubmit.py --baseline passes with valid API credentials
  • โ€”[ ] outputs/evals/baseline_results.json is generated and committed (or attached)
  • โ€”[ ] Hugging Face Space is deployed and responds to /health and /reset

๐Ÿ“จ Submission Portal Inputs

Use these exact links in the hackathon submission form:

  • โ€”GitHub Repository URL: https://github.com/<your-username>/<your-repo>
  • โ€”Hugging Face Space URL: https://huggingface.co/spaces/b4rty/torchdebug-env

Optional live runtime URL (for your own checks):

  • โ€”https://b4rty-torchdebug-env.hf.space

๐Ÿงพ Final One-Command Validation

After setting env vars (API_BASE_URL, MODEL_NAME, HF_TOKEN), run:

bash
python presubmit.py --docker --baseline
bash scripts/validate-submission.sh https://b4rty-torchdebug-env.hf.space .

This generates/updates:

  • โ€”outputs/evals/submission_report.json
  • โ€”outputs/evals/baseline_results.json