Tejasva commited on
Commit Β·
557bac4
1
Parent(s): 1596f8f
fix: update HF router config and add required logs
Browse files- inference.py +31 -11
inference.py
CHANGED
|
@@ -20,20 +20,22 @@ logger = logging.getLogger(__name__)
|
|
| 20 |
|
| 21 |
def setup_openai_client() -> tuple[OpenAI, str]:
|
| 22 |
"""Initialize OpenAI client from environment variables."""
|
| 23 |
-
api_base_url = os.getenv('API_BASE_URL')
|
| 24 |
-
model_name = os.getenv('MODEL_NAME', '
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
|
| 29 |
-
if not
|
| 30 |
-
raise ValueError("
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
return
|
| 37 |
|
| 38 |
def create_adaptive_prompt(observation: Dict[str, Any], step_type: str, agent_state: AgentState) -> str:
|
| 39 |
"""Create adaptive prompt based on agent learning state."""
|
|
@@ -159,6 +161,7 @@ def run_llm_inference(client: OpenAI, model_name: str, prompt: str) -> str:
|
|
| 159 |
|
| 160 |
def run_baseline(env: CodeGuardianEnv) -> float:
|
| 161 |
"""Run a simple non-learning baseline agent for comparison."""
|
|
|
|
| 162 |
logger.info("[BASELINE START] Running baseline agent...")
|
| 163 |
|
| 164 |
obs = env.reset()
|
|
@@ -185,6 +188,7 @@ def run_baseline(env: CodeGuardianEnv) -> float:
|
|
| 185 |
|
| 186 |
logger.info(f"[BASELINE STEP] {step_count}: {step_type} -> reward={reward.value:+.3f}")
|
| 187 |
|
|
|
|
| 188 |
logger.info(f"[BASELINE END] Total reward: {total_reward:.3f}, Steps: {step_count}")
|
| 189 |
return total_reward
|
| 190 |
|
|
@@ -234,6 +238,7 @@ def run_episode(env: CodeGuardianEnv, client: OpenAI, model_name: str, agent_sta
|
|
| 234 |
episode_history = []
|
| 235 |
step_count = 0
|
| 236 |
|
|
|
|
| 237 |
logger.info(f"[EPISODE START] Episode {agent_state.episode + 1} - model={model_name} task_id={obs.task_id} difficulty={obs.difficulty}")
|
| 238 |
|
| 239 |
while not env.done:
|
|
@@ -242,6 +247,8 @@ def run_episode(env: CodeGuardianEnv, client: OpenAI, model_name: str, agent_sta
|
|
| 242 |
step_type = step_types[current_step]
|
| 243 |
|
| 244 |
step_count += 1
|
|
|
|
|
|
|
| 245 |
logger.info(f"[STEP] step_number={step_count} step_type={step_type} task_id={obs.task_id}")
|
| 246 |
|
| 247 |
# Create adaptive prompt
|
|
@@ -303,6 +310,7 @@ def run_episode(env: CodeGuardianEnv, client: OpenAI, model_name: str, agent_sta
|
|
| 303 |
break
|
| 304 |
|
| 305 |
# Final episode log
|
|
|
|
| 306 |
logger.info(f"[EPISODE END] Episode {agent_state.episode + 1} - final_score={episode_reward:.3f} total_steps={step_count} strategy={agent_state.prompt_strategy}")
|
| 307 |
|
| 308 |
return episode_reward, episode_history
|
|
@@ -315,6 +323,7 @@ def train_agent(num_episodes: int = 10) -> AgentState:
|
|
| 315 |
agent_state = AgentState()
|
| 316 |
all_episodes = []
|
| 317 |
|
|
|
|
| 318 |
logger.info(f"[TRAINING START] Starting RL training for {num_episodes} episodes with model: {model_name}")
|
| 319 |
|
| 320 |
# RUN BASELINE FIRST
|
|
@@ -357,8 +366,9 @@ def train_agent(num_episodes: int = 10) -> AgentState:
|
|
| 357 |
break
|
| 358 |
|
| 359 |
# PERFORMANCE COMPARISON
|
|
|
|
| 360 |
logger.info(f"\n{'='*60}")
|
| 361 |
-
logger.info("[TRAINING SUMMARY]")
|
| 362 |
logger.info(f"{'='*60}")
|
| 363 |
|
| 364 |
# Calculate improvement over baseline
|
|
@@ -378,12 +388,16 @@ def train_agent(num_episodes: int = 10) -> AgentState:
|
|
| 378 |
|
| 379 |
# Performance classification
|
| 380 |
if improvement > 50:
|
|
|
|
| 381 |
logger.info("π EXCELLENT: Significant improvement over baseline!")
|
| 382 |
elif improvement > 20:
|
|
|
|
| 383 |
logger.info("β
GOOD: Measurable improvement achieved")
|
| 384 |
elif improvement > 0:
|
|
|
|
| 385 |
logger.info("π POSITIVE: Some improvement over baseline")
|
| 386 |
else:
|
|
|
|
| 387 |
logger.info("β οΈ NO IMPROVEMENT: RL agent not better than baseline")
|
| 388 |
|
| 389 |
return agent_state
|
|
@@ -395,11 +409,17 @@ def train_agent(num_episodes: int = 10) -> AgentState:
|
|
| 395 |
def main():
|
| 396 |
"""Main inference loop with RL training."""
|
| 397 |
try:
|
|
|
|
|
|
|
|
|
|
| 398 |
# Run RL training
|
| 399 |
agent_state = train_agent(num_episodes=10)
|
|
|
|
|
|
|
| 400 |
return 0
|
| 401 |
|
| 402 |
except Exception as e:
|
|
|
|
| 403 |
logger.error(f"Inference failed: {e}")
|
| 404 |
return 1
|
| 405 |
|
|
|
|
| 20 |
|
| 21 |
def setup_openai_client() -> tuple[OpenAI, str]:
|
| 22 |
"""Initialize OpenAI client from environment variables."""
|
| 23 |
+
api_base_url = os.getenv('API_BASE_URL', 'https://router.huggingface.co/v1')
|
| 24 |
+
model_name = os.getenv('MODEL_NAME', 'meta-llama/Llama-3-8b-instruct')
|
| 25 |
|
| 26 |
+
# Only use HF_TOKEN (remove API_KEY fallback)
|
| 27 |
+
hf_token = os.getenv('HF_TOKEN')
|
| 28 |
|
| 29 |
+
if not hf_token:
|
| 30 |
+
raise ValueError("HF_TOKEN environment variable is required")
|
| 31 |
|
| 32 |
+
# Initialize OpenAI client with base_url and api_key
|
| 33 |
+
client = OpenAI(
|
| 34 |
+
api_key=hf_token,
|
| 35 |
+
base_url=api_base_url
|
| 36 |
+
)
|
| 37 |
|
| 38 |
+
return client, model_name
|
| 39 |
|
| 40 |
def create_adaptive_prompt(observation: Dict[str, Any], step_type: str, agent_state: AgentState) -> str:
|
| 41 |
"""Create adaptive prompt based on agent learning state."""
|
|
|
|
| 161 |
|
| 162 |
def run_baseline(env: CodeGuardianEnv) -> float:
|
| 163 |
"""Run a simple non-learning baseline agent for comparison."""
|
| 164 |
+
print("START: Running baseline agent...")
|
| 165 |
logger.info("[BASELINE START] Running baseline agent...")
|
| 166 |
|
| 167 |
obs = env.reset()
|
|
|
|
| 188 |
|
| 189 |
logger.info(f"[BASELINE STEP] {step_count}: {step_type} -> reward={reward.value:+.3f}")
|
| 190 |
|
| 191 |
+
print(f"END: Baseline complete - Total reward: {total_reward:.3f}, Steps: {step_count}")
|
| 192 |
logger.info(f"[BASELINE END] Total reward: {total_reward:.3f}, Steps: {step_count}")
|
| 193 |
return total_reward
|
| 194 |
|
|
|
|
| 238 |
episode_history = []
|
| 239 |
step_count = 0
|
| 240 |
|
| 241 |
+
print(f"START: Episode {agent_state.episode + 1} - model={model_name} task_id={obs.task_id} difficulty={obs.difficulty}")
|
| 242 |
logger.info(f"[EPISODE START] Episode {agent_state.episode + 1} - model={model_name} task_id={obs.task_id} difficulty={obs.difficulty}")
|
| 243 |
|
| 244 |
while not env.done:
|
|
|
|
| 247 |
step_type = step_types[current_step]
|
| 248 |
|
| 249 |
step_count += 1
|
| 250 |
+
print(f"STEP: {step_type}")
|
| 251 |
+
print(f"STEP: {step_count} - {step_type} - task_id={obs.task_id}")
|
| 252 |
logger.info(f"[STEP] step_number={step_count} step_type={step_type} task_id={obs.task_id}")
|
| 253 |
|
| 254 |
# Create adaptive prompt
|
|
|
|
| 310 |
break
|
| 311 |
|
| 312 |
# Final episode log
|
| 313 |
+
print(f"END: Episode {agent_state.episode + 1} - final_score={episode_reward:.3f} total_steps={step_count} strategy={agent_state.prompt_strategy}")
|
| 314 |
logger.info(f"[EPISODE END] Episode {agent_state.episode + 1} - final_score={episode_reward:.3f} total_steps={step_count} strategy={agent_state.prompt_strategy}")
|
| 315 |
|
| 316 |
return episode_reward, episode_history
|
|
|
|
| 323 |
agent_state = AgentState()
|
| 324 |
all_episodes = []
|
| 325 |
|
| 326 |
+
print(f"START: RL training for {num_episodes} episodes with model: {model_name}")
|
| 327 |
logger.info(f"[TRAINING START] Starting RL training for {num_episodes} episodes with model: {model_name}")
|
| 328 |
|
| 329 |
# RUN BASELINE FIRST
|
|
|
|
| 366 |
break
|
| 367 |
|
| 368 |
# PERFORMANCE COMPARISON
|
| 369 |
+
print("START: Training summary analysis")
|
| 370 |
logger.info(f"\n{'='*60}")
|
| 371 |
+
logger.info(f"[TRAINING SUMMARY]")
|
| 372 |
logger.info(f"{'='*60}")
|
| 373 |
|
| 374 |
# Calculate improvement over baseline
|
|
|
|
| 388 |
|
| 389 |
# Performance classification
|
| 390 |
if improvement > 50:
|
| 391 |
+
print("π EXCELLENT: Significant improvement over baseline!")
|
| 392 |
logger.info("π EXCELLENT: Significant improvement over baseline!")
|
| 393 |
elif improvement > 20:
|
| 394 |
+
print("β
GOOD: Measurable improvement achieved")
|
| 395 |
logger.info("β
GOOD: Measurable improvement achieved")
|
| 396 |
elif improvement > 0:
|
| 397 |
+
print("π POSITIVE: Some improvement over baseline")
|
| 398 |
logger.info("π POSITIVE: Some improvement over baseline")
|
| 399 |
else:
|
| 400 |
+
print("β οΈ NO IMPROVEMENT: RL agent not better than baseline")
|
| 401 |
logger.info("β οΈ NO IMPROVEMENT: RL agent not better than baseline")
|
| 402 |
|
| 403 |
return agent_state
|
|
|
|
| 409 |
def main():
|
| 410 |
"""Main inference loop with RL training."""
|
| 411 |
try:
|
| 412 |
+
# Required log at beginning
|
| 413 |
+
print("START: inference")
|
| 414 |
+
|
| 415 |
# Run RL training
|
| 416 |
agent_state = train_agent(num_episodes=10)
|
| 417 |
+
print("END: done")
|
| 418 |
+
logger.info("END: RL training completed successfully")
|
| 419 |
return 0
|
| 420 |
|
| 421 |
except Exception as e:
|
| 422 |
+
print(f"END: done")
|
| 423 |
logger.error(f"Inference failed: {e}")
|
| 424 |
return 1
|
| 425 |
|