Jeevan Kumar commited on
Commit
cee0b35
·
unverified ·
1 Parent(s): bd57080

Delete reference-material directory

Browse files
reference-material/.DS_Store DELETED
Binary file (6.15 kB)
 
reference-material/add_water_variable.py DELETED
@@ -1,59 +0,0 @@
1
- """
2
- add_water_variable.py
3
-
4
- Adds a Water_mm column to the farm dataset.
5
- Water is drawn uniformly from [WATER_MIN, Rainfall_mm].
6
- Rainfall_mm is reduced by the water drawn to prevent bias.
7
- """
8
-
9
- import pandas as pd
10
- import numpy as np
11
- import sys
12
-
13
- WATER_MIN = 20 # minimum meaningful irrigation (mm)
14
- WATER_MAX = 200 # hard ceiling - avoids flooding; also capped at rainfall
15
-
16
- def add_water(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
17
- rng = np.random.default_rng(seed)
18
- df = df.copy()
19
-
20
- # Upper bound: rainfall itself, capped at WATER_MAX
21
- upper = df["Rainfall_mm"].clip(upper=WATER_MAX)
22
-
23
- # Where rainfall < WATER_MIN we can't irrigate meaningfully — set 0
24
- can_irrigate = upper >= WATER_MIN
25
- water = np.where(
26
- can_irrigate,
27
- rng.uniform(WATER_MIN, upper.where(can_irrigate, WATER_MIN)),
28
- 0.0
29
- )
30
-
31
- df["Water_mm"] = np.round(water, 2)
32
- df["Rainfall_mm"] = np.round(df["Rainfall_mm"] - df["Water_mm"], 2)
33
- return df
34
-
35
-
36
- def main():
37
- path = sys.argv[1] if len(sys.argv) > 1 else "farm_data.csv"
38
- out = sys.argv[2] if len(sys.argv) > 2 else path.replace(".csv", "_watered.csv")
39
-
40
- df = pd.read_csv(path)
41
- required = {"Rainfall_mm"}
42
- missing = required - set(df.columns)
43
- if missing:
44
- raise ValueError(f"Missing columns: {missing}")
45
-
46
- df_out = add_water(df)
47
-
48
- print(f"Water_mm — min: {df_out['Water_mm'].min():.1f} "
49
- f"max: {df_out['Water_mm'].max():.1f} "
50
- f"mean: {df_out['Water_mm'].mean():.1f}")
51
- print(f"Rainfall_mm after subtraction — min: {df_out['Rainfall_mm'].min():.1f} "
52
- f"mean: {df_out['Rainfall_mm'].mean():.1f}")
53
-
54
- df_out.to_csv(out, index=False)
55
- print(f"Saved → {out}")
56
-
57
-
58
- if __name__ == "__main__":
59
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
reference-material/prevalidation-script.sh DELETED
@@ -1,192 +0,0 @@
1
- #!/usr/bin/env bash
2
- #
3
- # validate-submission.sh — OpenEnv Submission Validator
4
- #
5
- # Checks that your HF Space is live, Docker image builds, and openenv validate passes.
6
- #
7
- # Prerequisites:
8
- # - Docker: https://docs.docker.com/get-docker/
9
- # - openenv-core: pip install openenv-core
10
- # - curl (usually pre-installed)
11
- #
12
- # Run:
13
- # curl -fsSL https://raw.githubusercontent.com/<owner>/<repo>/main/scripts/validate-submission.sh | bash -s -- <ping_url> [repo_dir]
14
- #
15
- # Or download and run locally:
16
- # chmod +x validate-submission.sh
17
- # ./validate-submission.sh <ping_url> [repo_dir]
18
- #
19
- # Arguments:
20
- # ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)
21
- # repo_dir Path to your repo (default: current directory)
22
- #
23
- # Examples:
24
- # ./validate-submission.sh https://my-team.hf.space
25
- # ./validate-submission.sh https://my-team.hf.space ./my-repo
26
- #
27
-
28
- set -uo pipefail
29
-
30
- DOCKER_BUILD_TIMEOUT=600
31
- if [ -t 1 ]; then
32
- RED='\033[0;31m'
33
- GREEN='\033[0;32m'
34
- YELLOW='\033[1;33m'
35
- BOLD='\033[1m'
36
- NC='\033[0m'
37
- else
38
- RED='' GREEN='' YELLOW='' BOLD='' NC=''
39
- fi
40
-
41
- run_with_timeout() {
42
- local secs="$1"; shift
43
- if command -v timeout &>/dev/null; then
44
- timeout "$secs" "$@"
45
- elif command -v gtimeout &>/dev/null; then
46
- gtimeout "$secs" "$@"
47
- else
48
- "$@" &
49
- local pid=$!
50
- ( sleep "$secs" && kill "$pid" 2>/dev/null ) &
51
- local watcher=$!
52
- wait "$pid" 2>/dev/null
53
- local rc=$?
54
- kill "$watcher" 2>/dev/null
55
- wait "$watcher" 2>/dev/null
56
- return $rc
57
- fi
58
- }
59
-
60
- portable_mktemp() {
61
- local prefix="${1:-validate}"
62
- mktemp "${TMPDIR:-/tmp}/${prefix}-XXXXXX" 2>/dev/null || mktemp
63
- }
64
-
65
- CLEANUP_FILES=()
66
- cleanup() { rm -f "${CLEANUP_FILES[@]+"${CLEANUP_FILES[@]}"}"; }
67
- trap cleanup EXIT
68
-
69
- PING_URL="${1:-}"
70
- REPO_DIR="${2:-.}"
71
-
72
- if [ -z "$PING_URL" ]; then
73
- printf "Usage: %s <ping_url> [repo_dir]\n" "$0"
74
- printf "\n"
75
- printf " ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)\n"
76
- printf " repo_dir Path to your repo (default: current directory)\n"
77
- exit 1
78
- fi
79
-
80
- if ! REPO_DIR="$(cd "$REPO_DIR" 2>/dev/null && pwd)"; then
81
- printf "Error: directory '%s' not found\n" "${2:-.}"
82
- exit 1
83
- fi
84
- PING_URL="${PING_URL%/}"
85
- export PING_URL
86
- PASS=0
87
-
88
- log() { printf "[%s] %b\n" "$(date -u +%H:%M:%S)" "$*"; }
89
- pass() { log "${GREEN}PASSED${NC} -- $1"; PASS=$((PASS + 1)); }
90
- fail() { log "${RED}FAILED${NC} -- $1"; }
91
- hint() { printf " ${YELLOW}Hint:${NC} %b\n" "$1"; }
92
- stop_at() {
93
- printf "\n"
94
- printf "${RED}${BOLD}Validation stopped at %s.${NC} Fix the above before continuing.\n" "$1"
95
- exit 1
96
- }
97
-
98
- printf "\n"
99
- printf "${BOLD}========================================${NC}\n"
100
- printf "${BOLD} OpenEnv Submission Validator${NC}\n"
101
- printf "${BOLD}========================================${NC}\n"
102
- log "Repo: $REPO_DIR"
103
- log "Ping URL: $PING_URL"
104
- printf "\n"
105
-
106
- log "${BOLD}Step 1/3: Pinging HF Space${NC} ($PING_URL/reset) ..."
107
-
108
- CURL_OUTPUT=$(portable_mktemp "validate-curl")
109
- CLEANUP_FILES+=("$CURL_OUTPUT")
110
- HTTP_CODE=$(curl -s -o "$CURL_OUTPUT" -w "%{http_code}" -X POST \
111
- -H "Content-Type: application/json" -d '{}' \
112
- "$PING_URL/reset" --max-time 30 2>"$CURL_OUTPUT" || printf "000")
113
-
114
- if [ "$HTTP_CODE" = "200" ]; then
115
- pass "HF Space is live and responds to /reset"
116
- elif [ "$HTTP_CODE" = "000" ]; then
117
- fail "HF Space not reachable (connection failed or timed out)"
118
- hint "Check your network connection and that the Space is running."
119
- hint "Try: curl -s -o /dev/null -w '%%{http_code}' -X POST $PING_URL/reset"
120
- stop_at "Step 1"
121
- else
122
- fail "HF Space /reset returned HTTP $HTTP_CODE (expected 200)"
123
- hint "Make sure your Space is running and the URL is correct."
124
- hint "Try opening $PING_URL in your browser first."
125
- stop_at "Step 1"
126
- fi
127
-
128
- log "${BOLD}Step 2/3: Running docker build${NC} ..."
129
-
130
- if ! command -v docker &>/dev/null; then
131
- fail "docker command not found"
132
- hint "Install Docker: https://docs.docker.com/get-docker/"
133
- stop_at "Step 2"
134
- fi
135
-
136
- if [ -f "$REPO_DIR/Dockerfile" ]; then
137
- DOCKER_CONTEXT="$REPO_DIR"
138
- elif [ -f "$REPO_DIR/server/Dockerfile" ]; then
139
- DOCKER_CONTEXT="$REPO_DIR/server"
140
- else
141
- fail "No Dockerfile found in repo root or server/ directory"
142
- stop_at "Step 2"
143
- fi
144
-
145
- log " Found Dockerfile in $DOCKER_CONTEXT"
146
-
147
- BUILD_LOG=$(portable_mktemp "validate-build")
148
- CLEANUP_FILES+=("$BUILD_LOG")
149
-
150
- if run_with_timeout "$DOCKER_BUILD_TIMEOUT" docker build --progress=plain "$DOCKER_CONTEXT" 2>&1 | tee "$BUILD_LOG"; then
151
- pass "Docker build succeeded"
152
- else
153
- fail "Docker build failed (timeout=${DOCKER_BUILD_TIMEOUT}s)"
154
- tail -20 "$BUILD_LOG"
155
- stop_at "Step 2"
156
- fi
157
-
158
- log "${BOLD}Step 3/3: Running openenv validate${NC} ..."
159
-
160
- OPENENV_CMD=""
161
- if command -v openenv &>/dev/null; then
162
- OPENENV_CMD="$(command -v openenv)"
163
- elif [ -x "/Library/Frameworks/Python.framework/Versions/3.13/bin/openenv" ]; then
164
- OPENENV_CMD="/Library/Frameworks/Python.framework/Versions/3.13/bin/openenv"
165
- fi
166
-
167
- if [ -z "$OPENENV_CMD" ]; then
168
- fail "openenv command not found"
169
- hint "Install it: pip install openenv-core"
170
- hint "Or ensure /Library/Frameworks/Python.framework/Versions/3.13/bin is in PATH"
171
- stop_at "Step 3"
172
- fi
173
-
174
- VALIDATE_LOG=$(portable_mktemp "validate-openenv")
175
- CLEANUP_FILES+=("$VALIDATE_LOG")
176
-
177
- if (cd "$REPO_DIR" && "$OPENENV_CMD" validate 2>&1 | tee "$VALIDATE_LOG"); then
178
- pass "openenv validate passed"
179
- else
180
- fail "openenv validate failed"
181
- tail -50 "$VALIDATE_LOG"
182
- stop_at "Step 3"
183
- fi
184
-
185
- printf "\n"
186
- printf "${BOLD}========================================${NC}\n"
187
- printf "${GREEN}${BOLD} All 3/3 checks passed!${NC}\n"
188
- printf "${GREEN}${BOLD} Your submission is ready to submit.${NC}\n"
189
- printf "${BOLD}========================================${NC}\n"
190
- printf "\n"
191
-
192
- exit 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
reference-material/roadmap.md DELETED
@@ -1,577 +0,0 @@
1
- # FarmRL Round-1 Fast Development Roadmap
2
-
3
- ## Reference Materials
4
-
5
- ### Introduction
6
-
7
- FarmRL is a reinforcement learning project that trains an agent to manage crop farming decisions. Given observable farm conditions such as soil properties, weather, and crop type, the agent learns to control irrigation, fertilizer application, and pesticide use in order to maximise crop yield while maintaining a healthy sustainability score.
8
-
9
- The project is grounded in a tabular agricultural dataset and draws conceptual inspiration from the FarmGym simulation framework. Two training paradigms are supported: a classic RL agent via a custom OpenEnv environment, and an optional text-framing path using TRL for language-model-based decision making.
10
-
11
- The raw CSV dataset is preprocessed once. The preprocessing adds the Water\_mm column (drawn uniformly from [20, min(Rainfall\_mm, 200)]) and subtracts that value from Rainfall\_mm to preserve water-balance invariance. A lightweight regression model (XGBoost) is then trained on the processed data to serve as the environment's transition model.
12
-
13
- ---
14
-
15
- ## Dataset preprocessing requirement
16
-
17
- Add a preprocessing script that creates a new variable Water\_mm such that:
18
-
19
- Rainfall\_original = Rainfall\_new + Water\_mm
20
-
21
- This prevents bias by conserving total water availability.
22
-
23
- Script file:
24
-
25
- scripts/add\_water\_variable.py
26
-
27
- ```
28
- """
29
- add_water_variable.py
30
-
31
- Adds a Water_mm column to the farm dataset.
32
- Water is drawn uniformly from [WATER_MIN, Rainfall_mm].
33
- Rainfall_mm is reduced by the water drawn to prevent bias.
34
- """
35
-
36
- import pandas as pd
37
- import numpy as np
38
- import sys
39
-
40
- WATER_MIN = 20 # minimum meaningful irrigation (mm)
41
- WATER_MAX = 200 # hard ceiling - avoids flooding; also capped at rainfall
42
-
43
- def add_water(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
44
- rng = np.random.default_rng(seed)
45
- df = df.copy()
46
-
47
- # Upper bound: rainfall itself, capped at WATER_MAX
48
- upper = df["Rainfall_mm"].clip(upper=WATER_MAX)
49
-
50
- # Where rainfall < WATER_MIN we can't irrigate meaningfully — set 0
51
- can_irrigate = upper >= WATER_MIN
52
- water = np.where(
53
- can_irrigate,
54
- rng.uniform(WATER_MIN, upper.where(can_irrigate, WATER_MIN)),
55
- 0.0
56
- )
57
-
58
- df["Water_mm"] = np.round(water, 2)
59
- df["Rainfall_mm"] = np.round(df["Rainfall_mm"] - df["Water_mm"], 2)
60
- return df
61
-
62
-
63
- def main():
64
- path = sys.argv[1] if len(sys.argv) > 1 else "farm_data.csv"
65
- out = sys.argv[2] if len(sys.argv) > 2 else path.replace(".csv", "_watered.csv")
66
-
67
- df = pd.read_csv(path)
68
- required = {"Rainfall_mm"}
69
- missing = required - set(df.columns)
70
- if missing:
71
- raise ValueError(f"Missing columns: {missing}")
72
-
73
- df_out = add_water(df)
74
-
75
- print(f"Water_mm — min: {df_out['Water_mm'].min():.1f} "
76
- f"max: {df_out['Water_mm'].max():.1f} "
77
- f"mean: {df_out['Water_mm'].mean():.1f}")
78
- print(f"Rainfall_mm after subtraction — min: {df_out['Rainfall_mm'].min():.1f} "
79
- f"mean: {df_out['Rainfall_mm'].mean():.1f}")
80
-
81
- df_out.to_csv(out, index=False)
82
- print(f"Saved → {out}")
83
-
84
-
85
- if __name__ == "__main__":
86
- main()
87
-
88
- ```
89
-
90
- Purpose:
91
-
92
- • introduces irrigation variable • prevents data leakage • preserves statistical consistency • improves realism of agent decisions
93
-
94
- ---
95
-
96
- # 3-Phase Fast Development Plan (3–4 hours)
97
-
98
- Goal: produce validator-compliant submission with improved reward design.
99
-
100
- Scope limitations:
101
-
102
- • simple environment dynamics • minimal dataset preprocessing • basic transition model • improved reward shaping only
103
-
104
- ---
105
-
106
- # Phase 1 — OpenEnv Environment (Core functionality)
107
-
108
- **Goal:** produce a valid OpenEnv-compliant environment that passes schema and endpoint checks.
109
-
110
- Estimated time: **1.5 hours**
111
-
112
- ---
113
-
114
- ## Tasks
115
-
116
- ### 1. Define typed state model (Pydantic)
117
-
118
- Keep small but realistic.
119
-
120
- Example variables:
121
-
122
- ```
123
- soil_moisture : float
124
- soil_ph : float
125
- temperature : float
126
- rainfall : float
127
- crop_stage : int
128
- day : int
129
-
130
- ```
131
-
132
- Requirements satisfied:
133
-
134
- - typed models required by OpenEnv spec
135
- - deterministic state structure
136
-
137
- ---
138
-
139
- ### 2. Define typed action model
140
-
141
- Discrete actions simplify LLM reliability:
142
-
143
- ```
144
- water : float (0–50)
145
- fertilizer : float (0–20)
146
- pesticide : float (0–10)
147
-
148
- ```
149
-
150
- Keep ranges bounded to stabilize scoring.
151
-
152
- ---
153
-
154
- ### 3. Implement environment class
155
-
156
- File:
157
-
158
- ```
159
- env/farm_env.py
160
-
161
- ```
162
-
163
- Must implement:
164
-
165
- ```
166
- reset()
167
- step(action)
168
- state()
169
-
170
- ```
171
-
172
- ---
173
-
174
- ### 4. Implement improved reward design (only sophistication added)
175
-
176
- Reward must reflect:
177
-
178
- - yield improvement
179
- - sustainability balance
180
- - penalty for overuse of chemicals
181
-
182
- Example reward:
183
-
184
- ```
185
- yield_score =
186
- 0.4 * soil_moisture
187
- + 0.3 * temperature_factor
188
- + 0.3 * rainfall_factor
189
-
190
- resource_penalty =
191
- 0.03 * fertilizer^1.2
192
- + 0.04 * pesticide^1.3
193
-
194
- sustainability_bonus =
195
- 0.2 * exp(-fertilizer/20)
196
- + 0.2 * exp(-pesticide/10)
197
-
198
- reward =
199
- yield_score
200
- + sustainability_bonus
201
- - resource_penalty
202
-
203
- ```
204
-
205
- Characteristics:
206
-
207
- - diminishing returns on fertilizer
208
- - discourages excessive pesticide
209
- - stable numeric range
210
- - smooth gradients
211
-
212
- ---
213
-
214
- ### 5. Episode termination rule
215
-
216
- ```
217
- max_days = 30
218
-
219
- ```
220
-
221
- Short episodes ensure runtime < 20 min.
222
-
223
- ---
224
-
225
- ### 6. Create openenv.yaml
226
-
227
- Define:
228
-
229
- ```
230
- environment metadata
231
- observation schema
232
- action schema
233
- reward schema
234
- task definitions
235
-
236
- ```
237
-
238
- Ensure field names exactly match Pydantic models.
239
-
240
- ---
241
-
242
- ### 7. Implement API wrapper (if required by spec)
243
-
244
- Expose:
245
-
246
- ```
247
- POST /reset
248
- POST /step
249
- GET /state
250
-
251
- ```
252
-
253
- Ensure reset returns valid initial state.
254
-
255
- Requirement satisfied:
256
-
257
- HF Space ping must return 200.
258
-
259
- ---
260
-
261
- # Phase 2 — inference pipeline + tasks + graders
262
-
263
- **Goal:** produce valid evaluation run with structured logs and normalized scores.
264
-
265
- Estimated time: **1.5 hours**
266
-
267
- ---
268
-
269
- ## Tasks
270
-
271
- ### 1. Create inference.py in root directory
272
-
273
- File location:
274
-
275
- ```
276
- /inference.py
277
-
278
- ```
279
-
280
- Must:
281
-
282
- - load environment
283
- - call LLM via OpenAI client
284
- - run episodes
285
- - log structured output
286
- - compute task scores
287
-
288
- ---
289
-
290
- ### 2. Implement OpenAI client usage
291
-
292
- Must use env variables:
293
-
294
- ```
295
- API_BASE_URL
296
- MODEL_NAME
297
- HF_TOKEN
298
-
299
- ```
300
-
301
- LLM prompt format:
302
-
303
- ```
304
- Farm state:
305
- soil moisture: 34
306
- temperature: 26
307
- rainfall: 3
308
- crop stage: 2
309
-
310
- Choose action values:
311
- water
312
- fertilizer
313
- pesticide
314
-
315
- ```
316
-
317
- LLM output expected as JSON:
318
-
319
- ```
320
- {
321
- "water": 20,
322
- "fertilizer": 5,
323
- "pesticide": 1
324
- }
325
-
326
- ```
327
-
328
- Add fallback defaults if parsing fails.
329
-
330
- ---
331
-
332
- ### 3. Define 3 tasks
333
-
334
- Tasks must produce score ∈ [0,1].
335
-
336
- ---
337
-
338
- #### Task 1 — yield performance
339
-
340
- Measures productivity.
341
-
342
- ```
343
- score =
344
- normalized(total_reward)
345
-
346
- ```
347
-
348
- ---
349
-
350
- #### Task 2 — chemical efficiency
351
-
352
- Penalizes excessive fertilizer/pesticide.
353
-
354
- ```
355
- score =
356
- 1 - normalized(total_chemical_use)
357
-
358
- ```
359
-
360
- ---
361
-
362
- #### Task 3 — sustainability balance
363
-
364
- Encourages moderate actions.
365
-
366
- ```
367
- score =
368
- yield / (fertilizer + pesticide + 1)
369
- normalized to 0–1
370
-
371
- ```
372
-
373
- ---
374
-
375
- ### 4. Implement graders
376
-
377
- Each grader returns:
378
-
379
- ```
380
- {
381
- "task_id": "...",
382
- "score": float
383
- }
384
-
385
- ```
386
-
387
- Ensure:
388
-
389
- ```
390
- 0 ≤ score ≤ 1
391
-
392
- ```
393
-
394
- Validator requirement.
395
-
396
- ---
397
-
398
- ### 5. Implement structured logs
399
-
400
- Strict format:
401
-
402
- ```
403
- [START]
404
- model: MODEL_NAME
405
-
406
- [STEP]
407
- step: 1
408
- action: {...}
409
- reward: ...
410
-
411
- [STEP]
412
- step: 2
413
- ...
414
-
415
- [END]
416
- task_scores:
417
- task1: 0.63
418
- task2: 0.71
419
- task3: 0.59
420
-
421
- ```
422
-
423
- Formatting must match specification exactly.
424
-
425
- ---
426
-
427
- ### 6. Runtime optimization
428
-
429
- Keep small:
430
-
431
- ```
432
- episodes = 3
433
- steps per episode = 20–30
434
-
435
- ```
436
-
437
- Ensures runtime well below 20 minutes.
438
-
439
- ---
440
-
441
- # Phase 3 — packaging, docker, validation
442
-
443
- **Goal:** ensure infrastructure compatibility and reproducibility.
444
-
445
- Estimated time: **1 hour**
446
-
447
- ---
448
-
449
- ## Tasks
450
-
451
- ### 1. requirements.txt
452
-
453
- Minimal dependencies:
454
-
455
- ```
456
- pydantic
457
- numpy
458
- pyyaml
459
- openai
460
- fastapi (optional)
461
- uvicorn (optional)
462
-
463
- ```
464
-
465
- Avoid heavy ML libraries.
466
-
467
- ---
468
-
469
- ### 2. Dockerfile
470
-
471
- Must build automatically.
472
-
473
- Example flow:
474
-
475
- ```
476
- FROM python:3.11-slim
477
-
478
- WORKDIR /app
479
-
480
- COPY . .
481
-
482
- RUN pip install -r requirements.txt
483
-
484
- CMD ["python", "inference.py"]
485
-
486
- ```
487
-
488
- Validator requirement satisfied.
489
-
490
- ---
491
-
492
- ### 3. environment variables support
493
-
494
- Ensure inference.py reads:
495
-
496
- ```
497
- API_BASE_URL
498
- MODEL_NAME
499
- HF_TOKEN
500
-
501
- ```
502
-
503
- No hardcoding.
504
-
505
- ---
506
-
507
- ### 4. basic local tests
508
-
509
- Run:
510
-
511
- ```
512
- python inference.py
513
-
514
- ```
515
-
516
- Verify:
517
-
518
- - no crashes
519
- - scores generated
520
- - logs formatted correctly
521
-
522
- ---
523
-
524
- ### 5. validation checklist
525
-
526
- Confirm:
527
-
528
- HF Space can call:
529
-
530
- ```
531
- reset()
532
- step()
533
- state()
534
-
535
- ```
536
-
537
- Ensure:
538
-
539
- - numeric reward returned
540
- - valid JSON outputs
541
- - docker build successful
542
-
543
- ---
544
-
545
- # Final deliverable structure
546
-
547
- ```
548
- project/
549
-
550
- ├── openenv.yaml
551
- ├── inference.py
552
- ├── Dockerfile
553
- ├── requirements.txt
554
-
555
- ├── env/
556
- │ └── farm_env.py
557
-
558
- └── tasks/
559
- └── graders.py
560
-
561
- ```
562
-
563
- ---
564
-
565
- # Expected outcome
566
-
567
- Submission will pass:
568
-
569
- - OpenEnv compliance
570
- - structured logging requirement
571
- - 3 task requirement
572
- - reproducibility requirement
573
- - runtime constraint
574
- - docker build requirement
575
- - HF space endpoint validation
576
-
577
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
reference-material/sample-inference-script.py DELETED
@@ -1,188 +0,0 @@
1
- """
2
- Inference Script Example
3
- ===================================
4
- MANDATORY
5
- - Before submitting, ensure the following variables are defined in your environment configuration:
6
- API_BASE_URL The API endpoint for the LLM.
7
- MODEL_NAME The model identifier to use for inference.
8
- HF_TOKEN Your Hugging Face / API key.
9
- LOCAL_IMAGE_NAME The name of the local image to use for the environment if you are using from_docker_image()
10
- method
11
-
12
- - Defaults are set only for API_BASE_URL and MODEL_NAME
13
- (and should reflect your active inference setup):
14
- API_BASE_URL = os.getenv("API_BASE_URL", "<your-active-endpoint>")
15
- MODEL_NAME = os.getenv("MODEL_NAME", "<your-active-model>")
16
-
17
- - The inference script must be named `inference.py` and placed in the root directory of the project
18
- - Participants must use OpenAI Client for all LLM calls using above variables
19
-
20
- STDOUT FORMAT
21
- - The script must emit exactly three line types to stdout, in this order:
22
-
23
- [START] task=<task_name> env=<benchmark> model=<model_name>
24
- [STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>
25
- [END] success=<true|false> steps=<n> score=<score> rewards=<r1,r2,...,rn>
26
-
27
- Rules:
28
- - One [START] line at episode begin.
29
- - One [STEP] line per step, immediately after env.step() returns.
30
- - One [END] line after env.close(), always emitted (even on exception).
31
- - reward and rewards are formatted to 2 decimal places.
32
- - done and success are lowercase booleans: true or false.
33
- - error is the raw last_action_error string, or null if none.
34
- - All fields on a single line with no newlines within a line.
35
- - Each tasks should return score in [0, 1]
36
-
37
- Example:
38
- [START] task=click-test env=miniwob model=Qwen3-VL-30B
39
- [STEP] step=1 action=click('123') reward=0.00 done=false error=null
40
- [STEP] step=2 action=fill('456','text') reward=0.00 done=false error=null
41
- [STEP] step=3 action=click('789') reward=1.00 done=true error=null
42
- [END] success=true steps=3 score=1.00 rewards=0.00,0.00,1.00
43
- """
44
-
45
- import asyncio
46
- import os
47
- import textwrap
48
- from typing import List, Optional
49
-
50
- from openai import OpenAI
51
-
52
- from my_env_v4 import MyEnvV4Action, MyEnvV4Env
53
- IMAGE_NAME = os.getenv("IMAGE_NAME") # If you are using docker image
54
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
55
-
56
- API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
57
- MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
58
- TASK_NAME = os.getenv("MY_ENV_V4_TASK", "echo")
59
- BENCHMARK = os.getenv("MY_ENV_V4_BENCHMARK", "my_env_v4")
60
- MAX_STEPS = 8
61
- TEMPERATURE = 0.7
62
- MAX_TOKENS = 150
63
- SUCCESS_SCORE_THRESHOLD = 0.1 # normalized score in [0, 1]
64
-
65
- # Max possible reward: each token contributes 0.1, across all steps
66
- _MAX_REWARD_PER_STEP = MAX_TOKENS * 0.1
67
- MAX_TOTAL_REWARD = MAX_STEPS * _MAX_REWARD_PER_STEP
68
-
69
- SYSTEM_PROMPT = textwrap.dedent(
70
- """
71
- You are interacting with a simple echo environment.
72
- Each turn you must send a message. The environment will echo it back.
73
- Reward is proportional to message length: reward = len(message) * 0.1
74
- Your goal is to maximize total reward by sending meaningful, substantive messages.
75
- Reply with exactly one message string — no quotes, no prefixes, just the message text.
76
- """
77
- ).strip()
78
-
79
-
80
- def log_start(task: str, env: str, model: str) -> None:
81
- print(f"[START] task={task} env={env} model={model}", flush=True)
82
-
83
-
84
- def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
85
- error_val = error if error else "null"
86
- done_val = str(done).lower()
87
- print(
88
- f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",
89
- flush=True,
90
- )
91
-
92
-
93
- def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
94
- rewards_str = ",".join(f"{r:.2f}" for r in rewards)
95
- print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)
96
-
97
-
98
- def build_user_prompt(step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:
99
- history_block = "\n".join(history[-4:]) if history else "None"
100
- return textwrap.dedent(
101
- f"""
102
- Step: {step}
103
- Last echoed message: {last_echoed!r}
104
- Last reward: {last_reward:.2f}
105
- Previous steps:
106
- {history_block}
107
- Send your next message.
108
- """
109
- ).strip()
110
-
111
-
112
- def get_model_message(client: OpenAI, step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:
113
- user_prompt = build_user_prompt(step, last_echoed, last_reward, history)
114
- try:
115
- completion = client.chat.completions.create(
116
- model=MODEL_NAME,
117
- messages=[
118
- {"role": "system", "content": SYSTEM_PROMPT},
119
- {"role": "user", "content": user_prompt},
120
- ],
121
- temperature=TEMPERATURE,
122
- max_tokens=MAX_TOKENS,
123
- stream=False,
124
- )
125
- text = (completion.choices[0].message.content or "").strip()
126
- return text if text else "hello"
127
- except Exception as exc:
128
- print(f"[DEBUG] Model request failed: {exc}", flush=True)
129
- return "hello"
130
-
131
-
132
- async def main() -> None:
133
- client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
134
-
135
- env = await MyEnvV4Env.from_docker_image(IMAGE_NAME)
136
-
137
- history: List[str] = []
138
- rewards: List[float] = []
139
- steps_taken = 0
140
- score = 0.0
141
- success = False
142
-
143
- log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
144
-
145
- try:
146
- result = await env.reset() # OpenENV.reset()
147
- last_echoed = result.observation.echoed_message
148
- last_reward = 0.0
149
-
150
- for step in range(1, MAX_STEPS + 1):
151
- if result.done:
152
- break
153
-
154
- message = get_model_message(client, step, last_echoed, last_reward, history)
155
-
156
- result = await env.step(MyEnvV4Action(message=message))
157
- obs = result.observation
158
-
159
- reward = result.reward or 0.0
160
- done = result.done
161
- error = None
162
-
163
- rewards.append(reward)
164
- steps_taken = step
165
- last_echoed = obs.echoed_message
166
- last_reward = reward
167
-
168
- log_step(step=step, action=message, reward=reward, done=done, error=error)
169
-
170
- history.append(f"Step {step}: {message!r} -> reward {reward:+.2f}")
171
-
172
- if done:
173
- break
174
-
175
- score = sum(rewards) / MAX_TOTAL_REWARD if MAX_TOTAL_REWARD > 0 else 0.0
176
- score = min(max(score, 0.0), 1.0) # clamp to [0, 1]
177
- success = score >= SUCCESS_SCORE_THRESHOLD
178
-
179
- finally:
180
- try:
181
- await env.close()
182
- except Exception as e:
183
- print(f"[DEBUG] env.close() error (container cleanup): {e}", flush=True)
184
- log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
185
-
186
-
187
- if __name__ == "__main__":
188
- asyncio.run(main())