Skip to content

Commit b43f3fb

Browse files
committed
Make max compilation retries configurable via environment variable and chat commands
1 parent 14b8e7e commit b43f3fb

11 files changed

Lines changed: 107 additions & 20 deletions

File tree

MaxKernel/auto_agent/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
TPU_VERSION = os.environ.get("TPU_VERSION", "")
1313
RAG_CORPUS = os.environ.get("RAG_CORPUS", "")
1414
INCLUDE_THOUGHTS = os.environ.get("INCLUDE_THOUGHTS", "true").lower() == "true"
15+
MAX_COMPILATION_RETRIES = int(os.environ.get("MAX_COMPILATION_RETRIES", "6"))
1516

1617
# Model configuration
1718
model_config = types.GenerateContentConfig(

MaxKernel/auto_agent/subagents/kernel_writing/agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
load_kernel_and_plan_to_state,
1717
load_single_kernel_to_state,
1818
)
19-
from auto_agent.config import model_config, thinking_planner
19+
from auto_agent.config import model_config, thinking_planner, MAX_COMPILATION_RETRIES
2020
from auto_agent.constants import MODEL_NAME
2121
from auto_agent.custom_types import CustomLlmAgent
2222
from auto_agent.subagents.kernel_writing.kernel_compilation import (
@@ -46,15 +46,15 @@ class KernelCompilationValidationLoop(BaseAgent):
4646
compilation_checker: Optional[BaseAgent] = None
4747
fix_agent: Optional[BaseAgent] = None
4848
debug_agent: Optional[BaseAgent] = None
49-
max_retries: int = 4
49+
max_retries: int = 6
5050

5151
def __init__(
5252
self,
5353
name: str,
5454
compilation_checker: BaseAgent,
5555
fix_agent: BaseAgent,
5656
debug_agent: Optional[BaseAgent] = None,
57-
max_retries: int = 4,
57+
max_retries: int = 6,
5858
):
5959
super().__init__(
6060
name=name,
@@ -353,7 +353,7 @@ async def _run_async_impl(
353353
compilation_checker=kernel_compilation_checker_for_validation,
354354
fix_agent=fix_kernel_compilation_agent,
355355
debug_agent=add_debug_statements_agent,
356-
max_retries=6,
356+
max_retries=MAX_COMPILATION_RETRIES,
357357
)
358358

359359
kernel_compilation_summary_agent = CustomLlmAgent(

MaxKernel/auto_agent/subagents/kernel_writing/prompts/ask_validation_prompt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
YOUR TASK:
99
Present the user with clear options for what to do next:
1010
11-
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (up to 4 attempts)
11+
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (includes up to 6 automatic error-fixing attempts; you can ask me to change this limit at any time)
1212
2. **Generate Tests**: Skip validation and proceed directly to test generation
1313
3. **Something Else**: Ask a question or perform another action
1414

MaxKernel/auto_agent/subagents/profiling/agent.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,22 @@ async def _run_async_impl(
118118
),
119119
output_key="profiling_summary",
120120
include_contents="none",
121-
tools=[
122-
offline_tools.load_xplane_and_query,
123-
offline_tools.get_hlo_dump,
124-
offline_tools.create_chart_from_xplane,
125-
offline_tools.get_overview_page_metrics,
126-
vertex_ai_rag_tool,
127-
],
121+
tools=(
122+
[
123+
offline_tools.load_xplane_and_query,
124+
offline_tools.get_hlo_dump,
125+
offline_tools.create_chart_from_xplane,
126+
offline_tools.get_overview_page_metrics,
127+
vertex_ai_rag_tool,
128+
]
129+
if vertex_ai_rag_tool
130+
else [
131+
offline_tools.load_xplane_and_query,
132+
offline_tools.get_hlo_dump,
133+
offline_tools.create_chart_from_xplane,
134+
offline_tools.get_overview_page_metrics,
135+
]
136+
),
128137
)
129138

130139
# Main profiling orchestrator agent

MaxKernel/hitl_agent/agent.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@
3131
unified_test_agent,
3232
validated_test_generation_agent,
3333
)
34-
from hitl_agent.tools.tools import filesystem_tool_r, set_working_directory
34+
from hitl_agent.tools.tools import (
35+
filesystem_tool_r,
36+
set_working_directory,
37+
set_max_compilation_retries,
38+
)
3539

3640
# Root orchestration agent
3741
root_agent = CustomLlmAgent(
@@ -58,6 +62,7 @@
5862
tools=[
5963
filesystem_tool_r,
6064
set_working_directory,
65+
set_max_compilation_retries,
6166
], # Read-only access - orchestrator delegates writes to sub-agents
6267
instruction=interactive_prompt.PROMPT,
6368
description="Orchestrates the human-in-the-loop kernel generation process with GPU to JAX conversion capability.",

MaxKernel/hitl_agent/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
TPU_VERSION = os.environ.get("TPU_VERSION", "")
1313
RAG_CORPUS = os.environ.get("RAG_CORPUS", "")
1414
INCLUDE_THOUGHTS = os.environ.get("INCLUDE_THOUGHTS", "true").lower() == "true"
15+
MAX_COMPILATION_RETRIES = int(os.environ.get("MAX_COMPILATION_RETRIES", "6"))
1516

1617
# Model configuration
1718
model_config = types.GenerateContentConfig(

MaxKernel/hitl_agent/prompts/interactive_prompt.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,11 @@
1111
1212
1. **Filesystem Tool (Read-Only)**: You have a `filesystem_tool` that can **only read and list files** - you cannot write files. All file writing must be delegated to the appropriate sub-agents. Assume that all files you need to read are located in {workdir}. For example, if the user asks to read file `script.py`, you should call the tool with the path `{workdir}/script.py`.
1313
2. **Set Working Directory Tool**: You have a `set_working_directory` tool that can update the active workspace/working directory path for the session. Use this tool when the user requests to switch, set, or change the active working directory or workspace folder.
14-
3. **Specialist Sub-Agents**: You have a team of sub-agents you can delegate tasks to:
14+
3. **Set Max Compilation Retries Tool**: You have a `set_max_compilation_retries` tool that can update the maximum number of compilation validation and auto-fixing attempts. Use this tool when the user requests to set or change the maximum compilation retries or fixing attempts count.
15+
4. **Specialist Sub-Agents**: You have a team of sub-agents you can delegate tasks to:
1516
* **PlanKernelAgent**: Creates or revises optimization plans for Pallas kernels. Automatically presents plans to the user with approval options. Use for both new plans ("optimize X") and revisions ("change Y in the plan").
1617
* **ImplementKernelAgent**: Implements a Pallas kernel following an approved plan. Use ONLY after user approves the plan. Automatically asks the user about validation options after completion.
17-
* **ValidateKernelCompilationAgent**: Validates kernel compilation with automatic error fixing and debugging (up to 4 attempts). Use when user requests validation or wants to check compilation.
18+
* **ValidateKernelCompilationAgent**: Validates kernel compilation with automatic error fixing and debugging (up to 6 attempts by default; the user can ask you to change this limit). Use when user requests validation or wants to check compilation.
1819
* **ExplanationAgent**: Explains TPU or Pallas concepts.
1920
* **GenerateTestFileAgent**: Generates a comprehensive pytest test file with compilation, correctness, and performance tests for kernel files.
2021
* **UnifiedTestAgent**: Executes the generated pytest test file on TPU and provides comprehensive results including full tracebacks. Automatically manages server lifecycle (starts/stops TPU and eval servers as needed).
@@ -35,12 +36,16 @@
3536
* Is it profiling? (e.g., "Profile the kernel", "What are the bottlenecks?")
3637
* Is it GPU conversion? (e.g., "Convert CUDA to JAX", "Write JAX from PyTorch")
3738
* Is it setting/changing the workspace or working directory? (e.g., "Change working directory to /path/to/folder", "Set workspace folder to Y")
39+
* Is it changing the maximum compilation retries or attempts? (e.g., "Set max retries to 8", "Change max fixing attempts to 10")
3840
3941
2. **Execute the Plan**:
4042
4143
* **If the request is to CHANGE/SET the workspace or working directory**:
4244
* **Action**: Call `set_working_directory` tool with the absolute path.
4345
46+
* **If the request is to CHANGE/SET the maximum compilation retries**:
47+
* **Action**: Call `set_max_compilation_retries` tool with the integer value.
48+
4449
* **If the request is simple explanation** (like "What is a TPU?"):
4550
* **Action**: Delegate to `ExplanationAgent`.
4651

MaxKernel/hitl_agent/subagents/kernel_writing/agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
load_single_kernel_to_state,
1616
save_kernel_and_plan_paths,
1717
)
18-
from hitl_agent.config import model_config, thinking_planner
18+
from hitl_agent.config import model_config, thinking_planner, MAX_COMPILATION_RETRIES
1919
from hitl_agent.constants import MODEL_NAME
2020
from hitl_agent.custom_types import CustomLlmAgent
2121
from hitl_agent.subagents.kernel_writing.kernel_compilation import (
@@ -41,15 +41,15 @@ class KernelCompilationValidationLoop(BaseAgent):
4141
compilation_checker: Optional[BaseAgent] = None
4242
fix_agent: Optional[BaseAgent] = None
4343
debug_agent: Optional[BaseAgent] = None
44-
max_retries: int = 4
44+
max_retries: int = 6
4545

4646
def __init__(
4747
self,
4848
name: str,
4949
compilation_checker: BaseAgent,
5050
fix_agent: BaseAgent,
5151
debug_agent: Optional[BaseAgent] = None,
52-
max_retries: int = 4,
52+
max_retries: int = 6,
5353
):
5454
super().__init__(
5555
name=name,
@@ -372,7 +372,7 @@ async def _run_async_impl(
372372
compilation_checker=kernel_compilation_checker_for_validation,
373373
fix_agent=fix_kernel_compilation_agent,
374374
debug_agent=add_debug_statements_agent,
375-
max_retries=4,
375+
max_retries=MAX_COMPILATION_RETRIES,
376376
)
377377

378378
kernel_compilation_summary_agent = CustomLlmAgent(

MaxKernel/hitl_agent/subagents/kernel_writing/prompts/ask_validation_prompt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
YOUR TASK:
99
Present the user with clear options for what to do next:
1010
11-
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (up to 4 attempts)
11+
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (includes up to 6 automatic error-fixing attempts; you can ask me to change this limit at any time)
1212
2. **Generate Tests**: Skip validation and proceed directly to test generation
1313
3. **Something Else**: Ask a question or perform another action
1414
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""Tool for dynamically updating the max compilation retries setting."""
2+
3+
import logging
4+
import os
5+
from google.adk.tools import FunctionTool, ToolContext
6+
7+
8+
async def set_max_compilation_retries_fn(retries: int, tool_context: ToolContext) -> str:
9+
"""Set the maximum number of compilation validation and auto-fixing attempts.
10+
11+
Args:
12+
retries: The maximum number of attempts (must be positive).
13+
14+
Returns:
15+
A string containing the operation result description:
16+
- If successful: "Successfully updated maximum compilation retries to: <retries>"
17+
- If failed: "Error: The number of retries must be a positive integer."
18+
"""
19+
if retries <= 0:
20+
return "Error: The number of retries must be a positive integer."
21+
22+
# Update in-memory config variables
23+
import hitl_agent.config as hitl_cfg
24+
import auto_agent.config as auto_cfg
25+
hitl_cfg.MAX_COMPILATION_RETRIES = retries
26+
auto_cfg.MAX_COMPILATION_RETRIES = retries
27+
os.environ["MAX_COMPILATION_RETRIES"] = str(retries)
28+
29+
# Update .env file
30+
try:
31+
env_path = ".env"
32+
if os.path.exists(env_path):
33+
with open(env_path, "r") as f:
34+
lines = f.readlines()
35+
with open(env_path, "w") as f:
36+
updated = False
37+
for line in lines:
38+
if line.strip().startswith("MAX_COMPILATION_RETRIES="):
39+
f.write(f"MAX_COMPILATION_RETRIES={retries}\n")
40+
updated = True
41+
else:
42+
f.write(line)
43+
if not updated:
44+
f.write(f"MAX_COMPILATION_RETRIES={retries}\n")
45+
except Exception as e:
46+
logging.error(f"Failed to update .env: {e}")
47+
48+
# Update the active validation loops in-memory
49+
try:
50+
from hitl_agent.subagents.kernel_writing.agent import kernel_compilation_validation_loop as hitl_loop
51+
hitl_loop.max_retries = retries
52+
except Exception as e:
53+
logging.warning(f"Could not update hitl_loop max_retries: {e}")
54+
55+
try:
56+
from auto_agent.subagents.kernel_writing.agent import kernel_compilation_validation_loop as auto_loop
57+
auto_loop.max_retries = retries
58+
except Exception as e:
59+
logging.warning(f"Could not update auto_loop max_retries: {e}")
60+
61+
return f"Successfully updated maximum compilation retries to: {retries}"
62+
63+
64+
set_max_compilation_retries = FunctionTool(set_max_compilation_retries_fn)

0 commit comments

Comments
 (0)