Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (30)
- DockerfileAdded+89
- README.md+60-5
- __init__.pyAdded+16
- client.pyAdded+106
- implementation_plan.mdAdded+51
- inference.pyAdded+256
- models.pyAdded+38
- openenv.yamlAdded+7
- openenv_rtl_debugger.egg-info/PKG-INFOAdded+14
- openenv_rtl_debugger.egg-info/SOURCES.txtAdded+19
- openenv_rtl_debugger.egg-info/dependency_links.txtAdded+1
- openenv_rtl_debugger.egg-info/entry_points.txtAdded+2
- openenv_rtl_debugger.egg-info/requires.txtAdded+10
- openenv_rtl_debugger.egg-info/top_level.txtAdded+1
- planning.mdAdded+36
- pyproject.tomlAdded+50
- server/__init__.pyAdded+11
- server/app.pyAdded+84
- server/rtl_debugger_environment.pyAdded+333
- tasks/task2/context.mdAdded+1
- tasks/task2/design_active.vAdded+7
- tasks/task2/design_buggy.vAdded+7
- tasks/task2/makefileAdded+8
- tasks/task2/result.jsonAdded+49
- tasks/task2/results.xmlAdded+6
- tasks/task2/sim_build/cmds.fAdded+1
- tasks/task2/sim_build/sim.vvpAdded+29
- tasks/task2/test_xor_gate_simple.pyAdded+54
- uv.lockAdded
- validate_submission.shAdded+184
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Multi-stage build using openenv-base
# This Dockerfile is flexible and works for both:
# - In-repo environments (with local OpenEnv sources)
# - Standalone environments (with openenv from PyPI/Git)
# The build script (openenv build) handles context detection and sets appropriate build args.
ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
FROM ${BASE_IMAGE} AS builder
WORKDIR /app
# Ensure git, iverilog, and make are available
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
apt-get install -y --no-install-recommends git iverilog make && \
rm -rf /var/lib/apt/lists/*
# Build argument to control whether we're building standalone or in-repo
ARG BUILD_MODE=in-repo
ARG ENV_NAME=rtl_debugger
# Copy environment code (always at root of build context)
COPY . /app/env
# For in-repo builds, openenv is already vendored in the build context
# For standalone builds, openenv will be installed via pyproject.toml
WORKDIR /app/env
# Ensure uv is available (for local builds where base image lacks it)
RUN if ! command -v uv >/dev/null 2>&1; then \
curl -LsSf https://astral.sh/uv/install.sh | sh && \
mv /root/.local/bin/uv /usr/local/bin/uv && \
mv /root/.local/bin/uvx /usr/local/bin/uvx; \
fi
# Install dependencies using uv sync
# If uv.lock exists, use it; otherwise resolve on the fly
RUN --mount=type=cache,target=/root/.cache/uv \
if [ -f uv.lock ]; then \
uv sync --frozen --no-install-project --no-editable; \
else \
uv sync --no-install-project --no-editable; \
fi
RUN --mount=type=cache,target=/root/.cache/uv \
if [ -f uv.lock ]; then \
uv sync --frozen --no-editable; \
else \
uv sync --no-editable; \
fi
# Final runtime stage
FROM ${BASE_IMAGE}
# Install runtime dependencies (iverilog and make)
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
apt-get install -y --no-install-recommends iverilog make && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy the virtual environment from builder
COPY --from=builder /app/env/.venv /app/.venv
# Copy the environment code
COPY --from=builder /app/env /app/env
# Set PATH to use the virtual environment
ENV PATH="/app/.venv/bin:$PATH"
# Set PYTHONPATH so imports work correctly
ENV PYTHONPATH="/app/env:$PYTHONPATH"
ENV ENABLE_WEB_INTERFACE=true
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Run the FastAPI server
# The module path is constructed to work with the /app/env structure
CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]1234523456789101112131415161017181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465---title: RTL Openenvemoji: 🚀colorFrom: greencolorTo: purpletitle: RTL Debugger Environmentemoji: 🛠️colorFrom: bluecolorTo: greensdk: dockerpinned: falseapp_port: 8000base_path: /webtags: - openenv - verilog - rl - hardware-debugging---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# RTL Debugger Environment
The **RTL Debugger** is a Reinforcement Learning environment designed for automated hardware design fixing. It enables LLM-based agents to iteratively debug Verilog code.
## Quick Start
### 1. Build the EnvironmentThe environment runs in a Docker container to ensure all hardware tools (`iverilog`, `make`, `python-cocotb`) are correctly installed.
```bash# Build the image locallydocker build -t rtl_debugger-env:latest .```
### 2. Run the Server```bash# Start the environment server on port 8000docker run -p 8000:8000 --rm rtl_debugger-env:latest```Access the web UI at [http://localhost:8000/web](http://localhost:8000/web).
### 3. Run the Inference AgentWe provide a reference inference script that uses LLM to play the environment:
```bash# Install dependenciesuv sync
# Run the agent uv run python inference.py```
## Environment Details
### Action Model (`RtlDebuggerAction`)Agents submit their corrected Verilog module:- `fixed_code` (str): The full Verilog module source.
### Observation Model (`RtlDebuggerObservation`)The environment returns detailed hardware-centric feedback:- `design_code` (str): The initial (buggy) design for reference.- `feedback` (str): Raw output from `iverilog` errors or `cocotb` testbench logs.- `compiled` (bool): Whether the code successfully compiled.- `passed_tests` (bool): Whether all functional testcases passed.- `pass_rate` (float): Ratio of passed tests [0.0 - 1.0].- `levenshtein_distance` (int): Number of lines modified compared to the previous step.
---*Built with [OpenEnv](https://github.com/meta-pytorch/openenv-core)*.12345678910111213141516# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Rtl Debugger Environment."""
from .client import RtlDebuggerEnvfrom .models import RtlDebuggerAction, RtlDebuggerObservation
__all__ = [ "RtlDebuggerAction", "RtlDebuggerObservation", "RtlDebuggerEnv",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Rtl Debugger Environment Client."""
from typing import Dict
from openenv.core import EnvClientfrom openenv.core.client_types import StepResultfrom openenv.core.env_server.types import State
try: from .models import RtlDebuggerAction, RtlDebuggerObservationexcept ImportError: from models import RtlDebuggerAction, RtlDebuggerObservation # type: ignore
class RtlDebuggerEnv( EnvClient[RtlDebuggerAction, RtlDebuggerObservation, State]): """ Client for the Rtl Debugger Environment.
This client maintains a persistent WebSocket connection to the environment server, enabling efficient multi-step interactions with lower latency. Each client instance has its own dedicated environment session on the server.
Example: >>> # Connect to a running server >>> with RtlDebuggerEnv(base_url="http://localhost:8000") as client: ... result = client.reset() ... print(result.observation.echoed_message) ... ... result = client.step(RtlDebuggerAction(message="Hello!")) ... print(result.observation.echoed_message)
Example with Docker: >>> # Automatically start container and connect >>> client = RtlDebuggerEnv.from_docker_image("rtl_debugger-env:latest") >>> try: ... result = client.reset() ... result = client.step(RtlDebuggerAction(message="Test")) ... finally: ... client.close() """
def _step_payload(self, action: RtlDebuggerAction) -> Dict: """ Convert RtlDebuggerAction to JSON payload for step message.
Args: action: RtlDebuggerAction instance
Returns: Dictionary representation suitable for JSON encoding """ return { "fixed_code": action.fixed_code, }
def _parse_result(self, payload: Dict) -> StepResult[RtlDebuggerObservation]: """ Parse server response into StepResult[RtlDebuggerObservation].
Args: payload: JSON response data from server
Returns: StepResult with RtlDebuggerObservation """ obs_data = payload.get("observation", {}) observation = RtlDebuggerObservation( design_code=obs_data.get("design_code", ""), feedback=obs_data.get("feedback", ""), compiled=obs_data.get("compiled", False), passed_tests=obs_data.get("passed_tests", False), pass_rate=obs_data.get("pass_rate", 0.0), simulation_time=obs_data.get("simulation_time", 0.0), levenshtein_distance=obs_data.get("levenshtein_distance", 0), reward=obs_data.get("reward", 0.0), done=obs_data.get("done", False), )
return StepResult( observation=observation, reward=payload.get("reward", observation.reward), done=payload.get("done", observation.done), )
def _parse_state(self, payload: Dict) -> State: """ Parse server response into State object.
Args: payload: JSON response from state request
Returns: State object with episode_id and step_count """ return State( episode_id=payload.get("episode_id"), step_count=payload.get("step_count", 0), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Implement RTL Debugger Environment Evaluation using Cocotb
The goal is to update the RTL Debugger Environment to compute the new reward metrics based on Cocotb `make` results, parse [result.json](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/result.json), compute the final Grader Score, and update the Observation model.
## Proposed Changes
---
### Shared ModelsUpdate the observation and action models to reflect the new metrics.
#### [MODIFY] models.py- Ensure `fixed_code` is consistently used everywhere per your request. [RtlDebuggerAction](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/models.py#17-21) keeps `fixed_code: str`.- Add new metrics to [RtlDebuggerObservation](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/models.py#23-32): - `pass_rate: float = Field(default=0.0)` - `simulation_time: float = Field(default=0.0)` - `levenshtein_distance: int = Field(default=0)` - Modify `reward: float` field description.
---
### Core EnvironmentRevamp the simulation logic to utilize `make` and parse the cocotb output.
#### [MODIFY] server/rtl_debugger_environment.py- Fix references of `action.code` to `action.fixed_code`.- Add a dedicated `<grader>` function that computes the final score normalized between 0 and 1. `Score_final = PassRate` (LintWarnings subtracted if implemented later). It will be invoked at the end of the RL sequence.- Overwrite [step()](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/server/rtl_debugger_environment.py#109-167) method: 1. Write `action.fixed_code` to [design.v](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/design.v) inside a `temp_dir`. 2. Copy all files from `task_dir` (like [makefile](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/makefile) and Python tests) to `temp_dir`. 3. Calculate Levenshtein line distance between `self._design_code` and `action.fixed_code` using Python's built-in `difflib.ndiff` (no external dependency needed). 4. Explicitly test compilation using `iverilog -t null design.v`. If this fails, the process stops here, returning an observation indicating compilation failure and a negative reward. 5. If compilation passes, run `make` via `subprocess.run()`. 6. Read [result.json](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/result.json) if it exists. Extract `simulation_time` which is now populated directly by the testbench. 7. Calculate `pass_rate = num_passed / num_tests`, and assign it to the observation.
---
### Task FilesWe need to update the Task 2 testing script so it directly outputs simulation time.
#### [MODIFY] tasks/task2/test_xor_gate_simple.py- In the [test_xor_gate_simple.py](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/test_xor_gate_simple.py) testbench, inject simulation time into [result.json](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/result.json) automatically using `cocotb.utils.get_sim_time('ns')` at the end of the run.
---
## Verification Plan
### Automated Tests1. I'll verify the grader function by unit testing it manually within [app.py](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/server/app.py) or a scratch script.2. Ensure that it reports partial pass rates, proper simulation times, and levenstein line diff counts.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""Inference Script — RTL Debugger Environment============================================MANDATORY- Before submitting, ensure the following variables are set in your environment: API_BASE_URL The API endpoint for the LLM (e.g. https://router.huggingface.co/v1) MODEL_NAME The model identifier to use for inference. HF_TOKEN Your Hugging Face / API key.
- The inference script must be named `inference.py` and placed in the root of the project.- Participants must use the OpenAI client for all LLM calls using the above variables.
Workflow: 1. env.reset() returns the initial feedback (environment ready message). 2. Each step, the LLM receives: - The original buggy design.v (for reference) - The full conversation history of (code, feedback) pairs - The latest feedback (compiler errors or simulation output) 3. The LLM must reply with a complete Verilog module inside a ```verilog ... ``` block. 4. The extracted code is submitted as an action; the environment compiles and runs it. 5. Episode ends when all tests pass (done=True) or MAX_STEPS is reached."""
import osimport reimport textwrapimport timefrom typing import List, Tuple
# Load .env from this file's directory or any parent (picks up repo-root .env)try: from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv(usecwd=False)) # walks up from __file__ locationexcept ImportError: pass # dotenv not installed; rely on environment variables being set manually
from openai import OpenAI
try: from .client import RtlDebuggerEnv from .models import RtlDebuggerActionexcept ImportError: from client import RtlDebuggerEnv # type: ignore from models import RtlDebuggerAction # type: ignore
# --- Configuration -------------------------------------------------------------GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
if GEMINI_API_KEY: # Set defaults for Gemini (which uses an OpenAI-compatible endpoint) API_BASE_URL = os.getenv("API_BASE_URL") or "https://generativelanguage.googleapis.com/v1beta/openai/" API_KEY = GEMINI_API_KEY MODEL_NAME = os.getenv("MODEL_NAME") or "gemini-2.5-flash"else: # Fall back to Hugging Face router API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1" API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY") MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
TASK_NAME = os.getenv("RTL_DEBUGGER_TASK_NAME", "unknown-task")IMAGE_NAME = os.getenv("IMAGE_NAME")
MAX_STEPS = 8TEMPERATURE = 0.2MAX_TOKENS = 1024
# --- Prompts -------------------------------------------------------------------SYSTEM_PROMPT = textwrap.dedent( """ You are an expert Verilog hardware designer and debugger. Your task is to fix a buggy Verilog design module so that it passes all testcases.
Rules: - Reply with ONLY the corrected Verilog module, enclosed in a ```verilog ... ``` code block. - Do NOT include any explanation or commentary outside the code block. - Your code must compile with iverilog and pass all $display-based PASS/FAIL checks. - If there is a compilation error, carefully read the error and fix the syntax first. - If tests fail, read the simulation output and fix the logic. """).strip()
def _load_file(path: str) -> str: """Read a file, returning its contents or a placeholder if missing.""" try: with open(path, "r") as f: return f.read() except FileNotFoundError: return f"(file not found: {path})"
def _build_user_prompt( step: int, initial_design: str, history: List[Tuple[str, str]], latest_feedback: str,) -> str: """ Build the user prompt for the current step.
Args: step: Current step number (1-indexed). initial_design: The original buggy Verilog design. history: List of (code_submitted, feedback_received) from previous steps. latest_feedback: The most recent feedback from the environment. """ history_section = "" if history: history_lines = [] for i, (code, feedback) in enumerate(history[-4:], start=1): history_lines.append( f"--- Attempt {i} ---\n" f"```verilog\n{code.strip()}\n```\n" f"Feedback:\n{feedback.strip()}" ) history_section = "\n\nPrevious attempts:\n" + "\n\n".join(history_lines)
return textwrap.dedent( f""" Step {step} — Fix the Verilog design module.
--- Original (buggy) design --- ```verilog {initial_design.strip()} ```
{history_section}
--- Latest simulator feedback --- {latest_feedback.strip() or "(no output)"}
Reply with the corrected design module in a ```verilog ... ``` block. """ ).strip()
def _extract_verilog(response_text: str) -> str: """ Extract the Verilog code block from the LLM response.
Falls back to returning the entire response if no fenced block is found. """ match = re.search(r"```verilog\s*(.*?)```", response_text, re.DOTALL | re.IGNORECASE) if match: return match.group(1).strip()
# Try a plain ``` block match = re.search(r"```\s*(.*?)```", response_text, re.DOTALL) if match: return match.group(1).strip()
# Last resort: return the whole response return response_text.strip()
def _get_llm_response(llm: OpenAI, messages: List[dict], max_retries: int = 4) -> str: """Gets LLM response with basic retry logic for rate limits and temporary failures.""" for attempt in range(max_retries): try: completion = llm.chat.completions.create( model=MODEL_NAME, messages=messages, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, stream=False, ) return completion.choices[0].message.content or "" except Exception as exc: # Check for rate limit or retryable errors err_msg = str(exc).lower() if "rate limit" in err_msg or "too many requests" in err_msg or "temporary" in err_msg or attempt < max_retries - 1: wait_time = (2 ** attempt) * 2 # Exponential backoff: 2, 4, 8, 16... print(f"[Retry] Attempt {attempt + 1} failed: {exc}. Retrying in {wait_time}s...") time.sleep(wait_time) else: raise exc return ""
SERVER_URL = os.getenv("RTL_SERVER_URL", "http://localhost:8000")
def main() -> None: llm = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
history: List[Tuple[str, str]] = [] # (code, feedback) pairs rewards: List[float] = [] success = False num_steps = 0
with RtlDebuggerEnv(base_url=SERVER_URL).sync() as env: # Pass TASK_NAME if specified to select a specific task reset_options = {"TASK_NAME": TASK_NAME} if TASK_NAME and TASK_NAME != "unknown-task" else None result = env.reset(options=reset_options) obs = result.observation initial_design = obs.design_code latest_feedback = obs.feedback
print(f"[Reset] {latest_feedback}") if not initial_design: print("[End] success=False steps=0 rewards=[] score=0.0 (no design code received)") return
for step in range(1, MAX_STEPS + 1): if result.done: break
user_prompt = _build_user_prompt( step=step, initial_design=initial_design, history=history, latest_feedback=latest_feedback, )
messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}, ]
try: response_text = _get_llm_response(llm, messages) except Exception as exc: print(f"[Step] step={step} action=\"<llm_error>\" reward=0.0 done=False # {exc}") break
code = _extract_verilog(response_text) action_preview = code.replace("\n", "\\n")[:120]
result = env.step(RtlDebuggerAction(fixed_code=code)) obs = result.observation num_steps = step
latest_feedback = obs.feedback rewards.append(result.reward) history.append((code, obs.feedback)) success = result.done
print(f"[Step] step={step} action=\"{action_preview}...\" reward={result.reward:+.3f} done={result.done}") print(f" compiled={obs.compiled} | tests={obs.passed_tests} | pass_rate={obs.pass_rate:.2f} | sim_time={obs.simulation_time:.1f}ns | lev_dist={obs.levenshtein_distance}")
# Call the grader for the final score try: score = env.grade() except Exception: score = 0.0
print(f"[End] success={success} steps={num_steps} rewards={[round(r, 3) for r in rewards]} score={score:.3f}")
if __name__ == "__main__": main()
1234567891011121314151617181920212223242526272829303132333435363738# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Data models for the Rtl Debugger Environment.
The rtl_debugger environment is a simple test environment that echoes back messages."""
from openenv.core.env_server.types import Action, Observationfrom pydantic import Field
class RtlDebuggerAction(Action): """Action for the Rtl Debugger environment - submitting Verilog code."""
fixed_code: str = Field( ..., title="Verilog Code Submission", description="Paste your corrected Verilog design here. Ensure the module name and ports match the original.", )
class RtlDebuggerObservation(Observation): """Observation from the Rtl Debugger environment - compilation and simulation results."""
design_code: str = Field(default="", description="The current buggy design code to fix") feedback: str = Field(default="", description="Feedback from compilation or simulation") compiled: bool = Field(default=False, description="Whether the code compiled successfully") passed_tests: bool = Field(default=False, description="Whether all test cases passed") pass_rate: float = Field(default=0.0, description="Functional Pass Rate (0.0 to 1.0)") simulation_time: float = Field(default=0.0, description="Simulation time mapped from cocotb results") levenshtein_distance: int = Field(default=0, description="Number of lines changed") reward: float = Field(default=0.0, description="Final Reward / Score computed by the Grader") done: bool = Field(default=False, description="Whether the episode is done")1234567spec_version: 1name: rtl_debuggertype: spaceruntime: fastapiapp: server.app:appport: 8000
1234567891011121314Metadata-Version: 2.4
Name: openenv-rtl_debugger
Version: 0.1.0
Summary: Rtl Debugger environment for OpenEnv
Requires-Python: >=3.10
Requires-Dist: cocotb>=2.0.1
Requires-Dist: fastapi>=0.135.2
Requires-Dist: openai>=2.30.0
Requires-Dist: openenv-core[core]>=0.2.3
Requires-Dist: pydantic>=2.12.5
Requires-Dist: uvicorn>=0.42.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"12345678910111213141516171819README.md__init__.pyclient.pyinference.pymodels.pypyproject.toml./__init__.py./client.py./inference.py./models.pyopenenv_rtl_debugger.egg-info/PKG-INFOopenenv_rtl_debugger.egg-info/SOURCES.txtopenenv_rtl_debugger.egg-info/dependency_links.txtopenenv_rtl_debugger.egg-info/entry_points.txtopenenv_rtl_debugger.egg-info/requires.txtopenenv_rtl_debugger.egg-info/top_level.txtserver/__init__.pyserver/app.pyserver/rtl_debugger_environment.py1
12[console_scripts]server = rtl_debugger.server.app:main12345678910cocotb>=2.0.1fastapi>=0.135.2openai>=2.30.0openenv-core[core]>=0.2.3pydantic>=2.12.5uvicorn>=0.42.0
[dev]pytest>=8.0.0pytest-cov>=4.0.01rtl_debugger123456789101112131415161718192021222324252627282930313233343536## Environment:
The tasks involve debugging errors in verilog code.
First compile the task using iverilog
If compiled successfully then run make to run the cocotb testbench. Parse the output of the result.json produced to get the below 4 factors of reward rubric.
Check tasks/task2 for correct reference
## Reward rubric:
Compile Status: Did iverilog crash? (Binary: 0 or 1).
Pass Percentage: num_passed / num_tests from your JSON.
Simulation Time: How long did it run before an assertion hit?
Levenstein Distance (penalty): How many lines of code did the agent change?
We need a meaningful reward with partial progress signals
Later also look at giving partial progress based on waveform/timing correctness. We can consider: per-cycle correctness, transition correctness, stability award etc.
## The Grader (The "Judge")
The Grader is a binary or tiered evaluator that only cares about the Destination. It should be based on a passing the testbench. It's score varies between 0 and 1.
Metric 1: Functional Pass Rate. $\frac{Tests_{passed}}{Tests_{total}}$.
Metric 2: Structural Integrity. A Boolean check: Did the agent keep the same module name and ports? (Using a regex or a simple AST check).
Metric 3: Lint Cleanliness. Does it pass verilator --lint-only without warnings?The Grader's Formula:$$Score_{final} = (PassRate \times 100) - (LintWarnings \times 2)$$(If the code doesn't compile, the score is 0, period.)
(Metric 3 tbd later since i need to setup verilator first)
The grader should run instantly after the agent gives its final output.
# Inference.py
Simply calls an LLM used as a baseline to test the env.
to do:
more difficult tasks -> sequential, waveform analysis based, dut and tb both can be wrong so more probing required etc.
improve the partial progress reward signals
complete the grader
make it submission ready
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "openenv-rtl_debugger"version = "0.1.0"description = "Rtl Debugger environment for OpenEnv"requires-python = ">=3.10"dependencies = [ "cocotb>=2.0.1", # Core OpenEnv runtime (provides FastAPI server + HTTP client types) # install from github # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git", # Environment-specific dependencies # Add all dependencies needed for your environment here # Examples: # "numpy>=1.19.0", # "torch>=2.0.0", # "gymnasium>=0.29.0", # "openspiel>=1.0.0", # "smolagents>=1.22.0,<2", "fastapi>=0.135.2", "openai>=2.30.0", "openenv-core[core]>=0.2.3", "pydantic>=2.12.5", "uvicorn>=0.42.0",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "pytest-cov>=4.0.0",]
[project.scripts]# Server entry point - enables running via: uv run --project . server# or: python -m rtl_debugger.server.appserver = "rtl_debugger.server.app:main"
[tool.setuptools]include-package-data = truepackages = ["rtl_debugger", "rtl_debugger.server"]package-dir = { "rtl_debugger" = ".", "rtl_debugger.server" = "server" }1234567891011# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Rtl Debugger environment server components."""
from .rtl_debugger_environment import RtlDebuggerEnvironment
__all__ = ["RtlDebuggerEnvironment"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""FastAPI application for the Rtl Debugger Environment.
This module creates an HTTP server that exposes the RtlDebuggerEnvironmentover HTTP and WebSocket endpoints, compatible with EnvClient.
Endpoints: - POST /reset: Reset the environment - POST /step: Execute an action - GET /state: Get current environment state - GET /schema: Get action/observation schemas - WS /ws: WebSocket endpoint for persistent sessions
Usage: # Development (with auto-reload): uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
# Production: uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
# Or run directly: python -m server.app"""
try: from openenv.core.env_server.http_server import create_appexcept Exception as e: # pragma: no cover raise ImportError( "openenv is required for the web interface. Install dependencies with '\n uv sync\n'" ) from e
try: from models import RtlDebuggerAction, RtlDebuggerObservation from rtl_debugger_environment import RtlDebuggerEnvironmentexcept ModuleNotFoundError: from models import RtlDebuggerAction, RtlDebuggerObservation from server.rtl_debugger_environment import RtlDebuggerEnvironment
# Create the app with web interface and README integrationapp = create_app( RtlDebuggerEnvironment, RtlDebuggerAction, RtlDebuggerObservation, env_name="rtl_debugger", max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions)
def main(host: str = "0.0.0.0", port: int = 8000): """ Entry point for direct execution via uv run or python -m.
This function enables running the server without Docker: uv run --project . server uv run --project . server --port 8001 python -m rtl_debugger.server.app
Args: host: Host address to bind to (default: "0.0.0.0") port: Port number to listen on (default: 8000)
For production deployments, consider using uvicorn directly with multiple workers: uvicorn rtl_debugger.server.app:app --workers 4 """ import uvicorn
uvicorn.run(app, host=host, port=port)
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser() parser.add_argument("--port", type=int, default=8000) args = parser.parse_args() main(port=args.port)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Rtl Debugger Environment Implementation.
On reset(), a random task is loaded from the tasks/ directory.Each task folder must contain: design_buggy.v - the immutable original buggy module shown to the agent makefile - the cocotb makefile (must reference design_active.v) test_*.py - the cocotb testbench(es) that produce result.json
design_active.v is created on reset() as a mutable working copy of design_buggy.v.The agent overwrites design_active.v each step, so it iterates on its own previous fix."""
import difflibimport jsonimport osimport randomimport reimport shutilimport subprocessimport tracebackfrom uuid import uuid4
from openenv.core.env_server.interfaces import Environmentfrom openenv.core.env_server.types import State
try: from ..models import RtlDebuggerAction, RtlDebuggerObservationexcept ImportError: from models import RtlDebuggerAction, RtlDebuggerObservation
# Tasks directory is always at <package_root>/tasks/_TASKS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tasks"))
def _list_tasks() -> list[str]: """Return sorted list of task directory paths found under _TASKS_DIR.
A valid task must contain design_buggy.v and a makefile. """ if not os.path.isdir(_TASKS_DIR): return [] return sorted( os.path.join(_TASKS_DIR, name) for name in os.listdir(_TASKS_DIR) if os.path.isdir(os.path.join(_TASKS_DIR, name)) and os.path.exists(os.path.join(_TASKS_DIR, name, "design_buggy.v")) and os.path.exists(os.path.join(_TASKS_DIR, name, "makefile")) )
def _read(path: str) -> str: with open(path, "r") as f: return f.read()
def _levenshtein_line_distance(original: str, modified: str) -> int: """ Compute the number of changed lines between two strings using difflib. Counts lines that are added or removed (not unchanged context lines). """ orig_lines = original.splitlines(keepends=True) mod_lines = modified.splitlines(keepends=True) diffs = list(difflib.ndiff(orig_lines, mod_lines)) changed = sum(1 for d in diffs if d.startswith("+ ") or d.startswith("- ")) return changed
def grader(result_json: dict, module_name_original: str, submitted_code: str) -> float: """ The Grader — evaluates the agent's final output.
Metric 1: Functional Pass Rate = num_passed / num_tests (0.0 – 1.0) Metric 2: Structural Integrity = module name preserved (Boolean) — TBD Metric 3: Lint Cleanliness = TBD (verilator not yet set up)
Formula (current): Score_final = PassRate (in [0.0, 1.0])
Returns a float in [0.0, 1.0]. """ num_tests = result_json.get("num_tests", 1) num_passed = result_json.get("num_passed", 0) pass_rate = num_passed / num_tests if num_tests > 0 else 0.0
# Structural integrity: to be done later score = pass_rate return score
class RtlDebuggerEnvironment(Environment): """ RTL Debugging environment.
On reset(), a random task is selected from the tasks/ directory. - design_buggy.v is read and shown to agent as the original reference. - design_active.v is created as a fresh mutable copy of design_buggy.v.
On each step(), the agent submits revised code which: 1. Is written to design_active.v (overwrites the previous attempt). 2. Is compiled with iverilog — fatal gate if it fails. 3. Is simulated via `make` (cocotb + icarus). 4. Has result.json parsed for pass/fail metrics. 5. Levenshtein distance is measured from the *previous* design_active.v.
A separate grader() function computes the final normalized score [0,1]. """
SUPPORTS_CONCURRENT_SESSIONS: bool = True
def __init__(self): """Initialize the rtl_debugger environment.""" self._state = State(episode_id=str(uuid4()), step_count=0) self._task_dir: str = "" self._design_code: str = "" # contents of design_buggy.v (immutable reference) self._task_name: str = ""
@property def _active_design_path(self) -> str: return os.path.join(self._task_dir, "design_active.v")
def reset(self, options: dict | None = None) -> RtlDebuggerObservation: # type: ignore[override] """ Reset the environment and load a task.
Args: options: Optional dict that can contain 'TASK_NAME' to load a specific task. If not provided or invalid, a random task is selected.
Returns: RtlDebuggerObservation with the initial design and feedback. """ self._state = State(episode_id=str(uuid4()), step_count=0)
tasks = _list_tasks() if not tasks: return RtlDebuggerObservation( design_code="", feedback=f"No tasks found in {_TASKS_DIR}.", compiled=False, passed_tests=False, done=False, reward=0.0, )
# Handle explicit task selection via options selected_task_dir = None if options and "TASK_NAME" in options: target_name = options["TASK_NAME"] for t_dir in tasks: if os.path.basename(t_dir) == target_name: selected_task_dir = t_dir break if not selected_task_dir: selected_task_dir = random.choice(tasks)
self._task_dir = selected_task_dir self._task_name = os.path.basename(self._task_dir) buggy_path = os.path.join(self._task_dir, "design_buggy.v") self._design_code = _read(buggy_path)
# Initialise design_active.v from the buggy design shutil.copy(buggy_path, self._active_design_path)
return RtlDebuggerObservation( design_code=self._design_code, feedback=f"--- Task: {self._task_name} (Initial) ---\nLoaded. Fix the Verilog design so all tests pass.", compiled=False, passed_tests=False, done=False, reward=0.0, )
def step(self, action: RtlDebuggerAction) -> RtlDebuggerObservation: # type: ignore[override] """ Compile and simulate the submitted Verilog code against the task testbench.
Args: action: RtlDebuggerAction containing the revised code in fixed_code
Returns: RtlDebuggerObservation with compilation/simulation results and reward metrics """ self._state.step_count += 1 code = action.fixed_code
try: return self._step_impl(code) except Exception as exc: traceback.print_exc() return RtlDebuggerObservation( design_code=self._design_code, feedback=f"[Internal Server Error] {type(exc).__name__}: {exc}", compiled=False, passed_tests=False, pass_rate=0.0, simulation_time=0.0, levenshtein_distance=0, reward=-1.0, done=False, )
def _step_impl(self, code: str) -> RtlDebuggerObservation: """Inner step logic — writes to design_active.v and runs the testbench."""
# --- Levenshtein vs the *previous* design_active.v (last agent attempt) --- prev_active = _read(self._active_design_path) if os.path.exists(self._active_design_path) else self._design_code lev_distance = _levenshtein_line_distance(prev_active, code)
# --- 1. Write agent's code to design_active.v --- with open(self._active_design_path, "w") as f: f.write(code)
# --- 2. Compile check (mandatory gate) --- compile_cmd = ["iverilog", "-t", "null", "design_active.v"] compile_res = subprocess.run( compile_cmd, cwd=self._task_dir, capture_output=True, text=True )
if compile_res.returncode != 0: feedback = compile_res.stderr or compile_res.stdout return RtlDebuggerObservation( design_code=self._design_code, feedback=f"[Compile Error]\n{feedback}", compiled=False, passed_tests=False, pass_rate=0.0, simulation_time=0.0, levenshtein_distance=lev_distance, reward=-1.0, done=False, )
# --- 3. Run cocotb testbench via make in the task dir --- try: make_res = subprocess.run( ["make"], cwd=self._task_dir, capture_output=True, text=True, timeout=60, ) make_feedback = make_res.stdout + make_res.stderr except subprocess.TimeoutExpired: return RtlDebuggerObservation( design_code=self._design_code, feedback="[Simulation Timeout] Simulation timed out (possible infinite loop in RTL)", compiled=True, passed_tests=False, pass_rate=0.0, simulation_time=0.0, levenshtein_distance=lev_distance, reward=-5.0, done=False, )
# --- 4. Parse result.json (written by cocotb into the task dir) --- result_path = os.path.join(self._task_dir, "result.json") if not os.path.exists(result_path): return RtlDebuggerObservation( design_code=self._design_code, feedback=f"[Simulation Error - result.json not produced]\n{make_feedback}", compiled=True, passed_tests=False, pass_rate=0.0, simulation_time=0.0, levenshtein_distance=lev_distance, reward=-5.0, done=False, )
with open(result_path, "r") as f: result_data = json.load(f)
num_tests = result_data.get("num_tests", 1) num_passed = result_data.get("num_passed", 0) pass_rate = num_passed / num_tests if num_tests > 0 else 0.0 passed_all = result_data.get("passed", False) simulation_time = result_data.get("simulation_time", 0.0)
reward = pass_rate * 10.0 reward += simulation_time * 0.01 reward -= lev_distance * 0.02 if passed_all: reward += 20.0
feedback_lines = [ f"Compiled: OK | Tests: {num_passed}/{num_tests} passed | SimTime: {simulation_time} ns", make_feedback.strip(), ] feedback = "\n".join(filter(None, feedback_lines))
return RtlDebuggerObservation( design_code=self._design_code, feedback=feedback, compiled=True, passed_tests=passed_all, pass_rate=pass_rate, simulation_time=simulation_time, levenshtein_distance=lev_distance, reward=reward, done=passed_all, )
def grade(self) -> float: """ Public grader interface — call after the RL episode ends. Reads result.json from the last make run and returns a score in [0, 1]. Returns 0.0 if no result.json exists yet. """ result_path = os.path.join(self._task_dir, "result.json") if not self._task_dir or not os.path.exists(result_path): return 0.0 with open(result_path, "r") as f: result_data = json.load(f) return grader(result_data, self._design_code, "")
@property def state(self) -> State: """ Get the current environment state.
Returns: Current State with episode_id and step_count """ return self._state1Four bit counter with reset signal1234567module gate ( input wire a, input wire b, output wire y); assign y = a ^ b;endmodule1234567module gate (
input wire a,
input wire b,
output wire y
);
assign y = a & b;
endmodule12345678TOPLEVEL_LANG = verilog
VERILOG_SOURCES = design_active.v
TOPLEVEL = gate
COCOTB_TEST_MODULES = test_xor_gate_simple
SIM = icarus
include $(shell cocotb-config --makefiles)/Makefile.sim12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "passed": true, "num_tests": 4, "num_passed": 4, "num_failed": 0, "simulation_time": 4.0, "results": [ { "test_id": 0, "inputs": { "a": 0, "b": 0 }, "expected": 0, "actual": 0, "pass": true }, { "test_id": 1, "inputs": { "a": 0, "b": 1 }, "expected": 1, "actual": 1, "pass": true }, { "test_id": 2, "inputs": { "a": 1, "b": 0 }, "expected": 1, "actual": 1, "pass": true }, { "test_id": 3, "inputs": { "a": 1, "b": 1 }, "expected": 0, "actual": 0, "pass": true } ]}123456<testsuites name="results"> <testsuite name="all" package="all"> <property name="random_seed" value="1775413661" /> <testcase name="test_xor_gate_simple" classname="test_xor_gate_simple" file="/mnt/c/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/test_xor_gate_simple.py" lineno="6" time="0.0021092891693115234" sim_time_ns="4.0" ratio_time="1896.3734599299198" /> </testsuite></testsuites>1+timescale+1ns/1ps1234567891011121314151617181920212223242526272829#! /usr/bin/vvp:ivl_version "12.0 (stable)";:ivl_delay_selection "TYPICAL";:vpi_time_precision - 12;:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/system.vpi";:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/vhdl_sys.vpi";:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/vhdl_textio.vpi";:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/v2005_math.vpi";:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/va_math.vpi";:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/v2009.vpi";S_0x55e08223e510 .scope package, "$unit" "$unit" 2 1; .timescale -9 -12;S_0x55e08223e6a0 .scope module, "gate" "gate" 3 1; .timescale -9 -12; .port_info 0 /INPUT 1 "a"; .port_info 1 /INPUT 1 "b"; .port_info 2 /OUTPUT 1 "y";o0x7f3d4edcc018 .functor BUFZ 1, C4<z>; HiZ driveo0x7f3d4edcc048 .functor BUFZ 1, C4<z>; HiZ driveL_0x55e082285170 .functor XOR 1, o0x7f3d4edcc018, o0x7f3d4edcc048, C4<0>, C4<0>;v0x55e08224fd50_0 .net "a", 0 0, o0x7f3d4edcc018; 0 driversv0x55e082250430_0 .net "b", 0 0, o0x7f3d4edcc048; 0 driversv0x55e082285050_0 .net "y", 0 0, L_0x55e082285170; 1 drivers# The file index is used to find the file name in the following table.:file_names 4; "N/A"; "<interactive>"; "-"; "design_active.v";123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import cocotb
from cocotb.triggers import Timer
from cocotb.utils import get_sim_time
import json
@cocotb.test()
async def test_xor_gate_simple(dut):
"""Test XOR gate with simple inputs (structured output)"""
results = []
passed = True
test_cases = [
{"a": 0, "b": 0, "expected": 0},
{"a": 0, "b": 1, "expected": 1},
{"a": 1, "b": 0, "expected": 1},
{"a": 1, "b": 1, "expected": 0},
]
for i, tc in enumerate(test_cases):
dut.a.value = tc["a"]
dut.b.value = tc["b"]
await Timer(1, unit="ns")
actual = int(dut.y.value)
ok = (actual == tc["expected"])
if not ok:
passed = False
results.append({
"test_id": i,
"inputs": {"a": tc["a"], "b": tc["b"]},
"expected": tc["expected"],
"actual": actual,
"pass": ok
})
summary = {
"passed": passed,
"num_tests": len(test_cases),
"num_passed": sum(r["pass"] for r in results),
"num_failed": sum(not r["pass"] for r in results),
"simulation_time": get_sim_time("ns"),
"results": results
}
# ALWAYS write output (even if failing)
with open("result.json", "w") as f:
json.dump(summary, f, indent=2)
# Optional: still fail cocotb test for debugging (can remove later)
assert passed, "Some test cases failed"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184#!/usr/bin/env bash## validate-submission.sh - OpenEnv Submission Validator## Checks that your HF Space is live, Docker image builds, and openenv validate passes.## Prerequisites:# - Docker: https://docs.docker.com/get-docker/# - openenv-core: pip install openenv-core# - curl (usually pre-installed)## Run:# curl -fsSL https://raw.githubusercontent.com/<owner>/<repo>/main/scripts/validate-submission.sh | bash -s -- <ping_url> [repo_dir]## Or download and run locally:# chmod +x validate-submission.sh# ./validate-submission.sh <ping_url> [repo_dir]## Arguments:# ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)# repo_dir Path to your repo (default: current directory)## Examples:# ./validate-submission.sh https://my-team.hf.space# ./validate-submission.sh https://my-team.hf.space ./my-repo#
set -uo pipefail
DOCKER_BUILD_TIMEOUT=600if [ -t 1 ]; then RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BOLD='\033[1m' NC='\033[0m'else RED='' GREEN='' YELLOW='' BOLD='' NC=''fi
run_with_timeout() { local secs="$1"; shift if command -v timeout &>/dev/null; then timeout "$secs" "$@" elif command -v gtimeout &>/dev/null; then gtimeout "$secs" "$@" else "$@" & local pid=$! ( sleep "$secs" && kill "$pid" 2>/dev/null ) & local watcher=$! wait "$pid" 2>/dev/null local rc=$? kill "$watcher" 2>/dev/null wait "$watcher" 2>/dev/null return $rc fi}
portable_mktemp() { local prefix="${1:-validate}" mktemp "${TMPDIR:-/tmp}/${prefix}-XXXXXX" 2>/dev/null || mktemp}
CLEANUP_FILES=()cleanup() { rm -f "${CLEANUP_FILES[@]+"${CLEANUP_FILES[@]}"}"; }trap cleanup EXIT
PING_URL="${1:-}"REPO_DIR="${2:-.}"
if [ -z "$PING_URL" ]; then printf "Usage: %s <ping_url> [repo_dir]\n" "$0" printf "\n" printf " ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)\n" printf " repo_dir Path to your repo (default: current directory)\n" exit 1fi
if ! REPO_DIR="$(cd "$REPO_DIR" 2>/dev/null && pwd)"; then printf "Error: directory '%s' not found\n" "${2:-.}" exit 1fiPING_URL="${PING_URL%/}"export PING_URLPASS=0
log() { printf "[%s] %b\n" "$(date -u +%H:%M:%S)" "$*"; }pass() { log "${GREEN}PASSED${NC} -- $1"; PASS=$((PASS + 1)); }fail() { log "${RED}FAILED${NC} -- $1"; }hint() { printf " ${YELLOW}Hint:${NC} %b\n" "$1"; }stop_at() { printf "\n" printf "${RED}${BOLD}Validation stopped at %s.${NC} Fix the above before continuing.\n" "$1" exit 1}
printf "\n"printf "${BOLD}========================================${NC}\n"printf "${BOLD} OpenEnv Submission Validator${NC}\n"printf "${BOLD}========================================${NC}\n"log "Repo: $REPO_DIR"log "Ping URL: $PING_URL"printf "\n"
log "${BOLD}Step 1/3: Pinging HF Space${NC} ($PING_URL/reset) ..."
CURL_OUTPUT=$(portable_mktemp "validate-curl")CLEANUP_FILES+=("$CURL_OUTPUT")HTTP_CODE=$(curl -s -o "$CURL_OUTPUT" -w "%{http_code}" -X POST \ -H "Content-Type: application/json" -d '{}' \ "$PING_URL/reset" --max-time 30 2>"$CURL_OUTPUT" || printf "000")
if [ "$HTTP_CODE" = "200" ]; then pass "HF Space is live and responds to /reset"elif [ "$HTTP_CODE" = "000" ]; then fail "HF Space not reachable (connection failed or timed out)" hint "Check your network connection and that the Space is running." hint "Try: curl -s -o /dev/null -w '%%{http_code}' -X POST $PING_URL/reset" stop_at "Step 1"else fail "HF Space /reset returned HTTP $HTTP_CODE (expected 200)" hint "Make sure your Space is running and the URL is correct." hint "Try opening $PING_URL in your browser first." stop_at "Step 1"fi
log "${BOLD}Step 2/3: Running docker build${NC} ..."
if ! command -v docker &>/dev/null; then fail "docker command not found" hint "Install Docker: https://docs.docker.com/get-docker/" stop_at "Step 2"fi
if [ -f "$REPO_DIR/Dockerfile" ]; then DOCKER_CONTEXT="$REPO_DIR"elif [ -f "$REPO_DIR/server/Dockerfile" ]; then DOCKER_CONTEXT="$REPO_DIR/server"else fail "No Dockerfile found in repo root or server/ directory" stop_at "Step 2"fi
log " Found Dockerfile in $DOCKER_CONTEXT"
BUILD_OK=falseBUILD_OUTPUT=$(run_with_timeout "$DOCKER_BUILD_TIMEOUT" docker build "$DOCKER_CONTEXT" 2>&1) && BUILD_OK=true
if [ "$BUILD_OK" = true ]; then pass "Docker build succeeded"else fail "Docker build failed (timeout=${DOCKER_BUILD_TIMEOUT}s)" printf "%s\n" "$BUILD_OUTPUT" | tail -20 stop_at "Step 2"fi
log "${BOLD}Step 3/3: Running openenv validate${NC} ..."
if ! command -v openenv &>/dev/null; then fail "openenv command not found" hint "Install it: pip install openenv-core" stop_at "Step 3"fi
VALIDATE_OK=falseVALIDATE_OUTPUT=$(cd "$REPO_DIR" && openenv validate 2>&1) && VALIDATE_OK=true
if [ "$VALIDATE_OK" = true ]; then pass "openenv validate passed" [ -n "$VALIDATE_OUTPUT" ] && log " $VALIDATE_OUTPUT"else fail "openenv validate failed" printf "%s\n" "$VALIDATE_OUTPUT" stop_at "Step 3"fi
printf "\n"printf "${BOLD}========================================${NC}\n"printf "${GREEN}${BOLD} All 3/3 checks passed!${NC}\n"printf "${GREEN}${BOLD} Your submission is ready to submit.${NC}\n"printf "${BOLD}========================================${NC}\n"printf "\n"
DockerfileAdded+89
README.md+60-5
__init__.pyAdded+16
client.pyAdded+106
implementation_plan.mdAdded+51
inference.pyAdded+256
models.pyAdded+38
openenv.yamlAdded+7
openenv_rtl_debugger.egg-info/PKG-INFOAdded+14
openenv_rtl_debugger.egg-info/SOURCES.txtAdded+19
openenv_rtl_debugger.egg-info/dependency_links.txtAdded+1
openenv_rtl_debugger.egg-info/entry_points.txtAdded+2
openenv_rtl_debugger.egg-info/requires.txtAdded+10
openenv_rtl_debugger.egg-info/top_level.txtAdded+1
planning.mdAdded+36
pyproject.tomlAdded+50
server/__init__.pyAdded+11
server/app.pyAdded+84
server/rtl_debugger_environment.pyAdded+333
tasks/task2/context.mdAdded+1
tasks/task2/design_active.vAdded+7
tasks/task2/design_buggy.vAdded+7
tasks/task2/makefileAdded+8
tasks/task2/result.jsonAdded+49
tasks/task2/results.xmlAdded+6
tasks/task2/sim_build/cmds.fAdded+1
tasks/task2/sim_build/sim.vvpAdded+29
tasks/task2/test_xor_gate_simple.pyAdded+54
uv.lockAdded
validate_submission.shAdded+184