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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# FarmRL Round-1 Fast Development Roadmap

## Reference Materials

### Introduction

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.

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.

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.

---

## Dataset preprocessing requirement

Add a preprocessing script that creates a new variable Water\_mm such that:

Rainfall\_original = Rainfall\_new + Water\_mm

This prevents bias by conserving total water availability.

Script file:

scripts/add\_water\_variable.py

```
"""
add_water_variable.py

Adds a Water_mm column to the farm dataset.
Water is drawn uniformly from [WATER_MIN, Rainfall_mm].
Rainfall_mm is reduced by the water drawn to prevent bias.
"""

import pandas as pd
import numpy as np
import sys

WATER_MIN = 20   # minimum meaningful irrigation (mm)
WATER_MAX = 200  # hard ceiling - avoids flooding; also capped at rainfall

def add_water(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    df = df.copy()

    # Upper bound: rainfall itself, capped at WATER_MAX
    upper = df["Rainfall_mm"].clip(upper=WATER_MAX)

    # Where rainfall < WATER_MIN we can't irrigate meaningfully β€” set 0
    can_irrigate = upper >= WATER_MIN
    water = np.where(
        can_irrigate,
        rng.uniform(WATER_MIN, upper.where(can_irrigate, WATER_MIN)),
        0.0
    )

    df["Water_mm"] = np.round(water, 2)
    df["Rainfall_mm"] = np.round(df["Rainfall_mm"] - df["Water_mm"], 2)
    return df


def main():
    path = sys.argv[1] if len(sys.argv) > 1 else "farm_data.csv"
    out  = sys.argv[2] if len(sys.argv) > 2 else path.replace(".csv", "_watered.csv")

    df = pd.read_csv(path)
    required = {"Rainfall_mm"}
    missing = required - set(df.columns)
    if missing:
        raise ValueError(f"Missing columns: {missing}")

    df_out = add_water(df)

    print(f"Water_mm  β€” min: {df_out['Water_mm'].min():.1f}  "
          f"max: {df_out['Water_mm'].max():.1f}  "
          f"mean: {df_out['Water_mm'].mean():.1f}")
    print(f"Rainfall_mm after subtraction β€” min: {df_out['Rainfall_mm'].min():.1f}  "
          f"mean: {df_out['Rainfall_mm'].mean():.1f}")

    df_out.to_csv(out, index=False)
    print(f"Saved β†’ {out}")


if __name__ == "__main__":
    main()

```

Purpose:

β€’ introduces irrigation variable β€’ prevents data leakage β€’ preserves statistical consistency β€’ improves realism of agent decisions

---

# 3-Phase Fast Development Plan (3–4 hours)

Goal: produce validator-compliant submission with improved reward design.

Scope limitations:

β€’ simple environment dynamics β€’ minimal dataset preprocessing β€’ basic transition model β€’ improved reward shaping only

---

# Phase 1 β€” OpenEnv Environment (Core functionality)

**Goal:** produce a valid OpenEnv-compliant environment that passes schema and endpoint checks.

Estimated time: **1.5 hours**

---

## Tasks

### 1. Define typed state model (Pydantic)

Keep small but realistic.

Example variables:

```
soil_moisture : float
soil_ph       : float
temperature   : float
rainfall      : float
crop_stage    : int
day           : int

```

Requirements satisfied:

- typed models required by OpenEnv spec
- deterministic state structure

---

### 2. Define typed action model

Discrete actions simplify LLM reliability:

```
water       : float   (0–50)
fertilizer  : float   (0–20)
pesticide   : float   (0–10)

```

Keep ranges bounded to stabilize scoring.

---

### 3. Implement environment class

File:

```
env/farm_env.py

```

Must implement:

```
reset()
step(action)
state()

```

---

### 4. Implement improved reward design (only sophistication added)

Reward must reflect:

- yield improvement
- sustainability balance
- penalty for overuse of chemicals

Example reward:

```
yield_score =
    0.4 * soil_moisture
  + 0.3 * temperature_factor
  + 0.3 * rainfall_factor

resource_penalty =
    0.03 * fertilizer^1.2
  + 0.04 * pesticide^1.3

sustainability_bonus =
    0.2 * exp(-fertilizer/20)
  + 0.2 * exp(-pesticide/10)

reward =
    yield_score
  + sustainability_bonus
  - resource_penalty

```

Characteristics:

- diminishing returns on fertilizer
- discourages excessive pesticide
- stable numeric range
- smooth gradients

---

### 5. Episode termination rule

```
max_days = 30

```

Short episodes ensure runtime < 20 min.

---

### 6. Create openenv.yaml

Define:

```
environment metadata
observation schema
action schema
reward schema
task definitions

```

Ensure field names exactly match Pydantic models.

---

### 7. Implement API wrapper (if required by spec)

Expose:

```
POST /reset
POST /step
GET /state

```

Ensure reset returns valid initial state.

Requirement satisfied:

HF Space ping must return 200.

---

# Phase 2 β€” inference pipeline + tasks + graders

**Goal:** produce valid evaluation run with structured logs and normalized scores.

Estimated time: **1.5 hours**

---

## Tasks

### 1. Create inference.py in root directory

File location:

```
/inference.py

```

Must:

- load environment
- call LLM via OpenAI client
- run episodes
- log structured output
- compute task scores

---

### 2. Implement OpenAI client usage

Must use env variables:

```
API_BASE_URL
MODEL_NAME
HF_TOKEN

```

LLM prompt format:

```
Farm state:
soil moisture: 34
temperature: 26
rainfall: 3
crop stage: 2

Choose action values:
water
fertilizer
pesticide

```

LLM output expected as JSON:

```
{
 "water": 20,
 "fertilizer": 5,
 "pesticide": 1
}

```

Add fallback defaults if parsing fails.

---

### 3. Define 3 tasks

Tasks must produce score ∈ [0,1].

---

#### Task 1 β€” yield performance

Measures productivity.

```
score =
normalized(total_reward)

```

---

#### Task 2 β€” chemical efficiency

Penalizes excessive fertilizer/pesticide.

```
score =
1 - normalized(total_chemical_use)

```

---

#### Task 3 β€” sustainability balance

Encourages moderate actions.

```
score =
yield / (fertilizer + pesticide + 1)
normalized to 0–1

```

---

### 4. Implement graders

Each grader returns:

```
{
 "task_id": "...",
 "score": float
}

```

Ensure:

```
0 ≀ score ≀ 1

```

Validator requirement.

---

### 5. Implement structured logs

Strict format:

```
[START]
model: MODEL_NAME

[STEP]
step: 1
action: {...}
reward: ...

[STEP]
step: 2
...

[END]
task_scores:
task1: 0.63
task2: 0.71
task3: 0.59

```

Formatting must match specification exactly.

---

### 6. Runtime optimization

Keep small:

```
episodes = 3
steps per episode = 20–30

```

Ensures runtime well below 20 minutes.

---

# Phase 3 β€” packaging, docker, validation

**Goal:** ensure infrastructure compatibility and reproducibility.

Estimated time: **1 hour**

---

## Tasks

### 1. requirements.txt

Minimal dependencies:

```
pydantic
numpy
pyyaml
openai
fastapi (optional)
uvicorn (optional)

```

Avoid heavy ML libraries.

---

### 2. Dockerfile

Must build automatically.

Example flow:

```
FROM python:3.11-slim

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

CMD ["python", "inference.py"]

```

Validator requirement satisfied.

---

### 3. environment variables support

Ensure inference.py reads:

```
API_BASE_URL
MODEL_NAME
HF_TOKEN

```

No hardcoding.

---

### 4. basic local tests

Run:

```
python inference.py

```

Verify:

- no crashes
- scores generated
- logs formatted correctly

---

### 5. validation checklist

Confirm:

HF Space can call:

```
reset()
step()
state()

```

Ensure:

- numeric reward returned
- valid JSON outputs
- docker build successful

---

# Final deliverable structure

```
project/
β”‚
β”œβ”€β”€ openenv.yaml
β”œβ”€β”€ inference.py
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ requirements.txt
β”‚
β”œβ”€β”€ env/
β”‚   └── farm_env.py
β”‚
└── tasks/
    └── graders.py

```

---

# Expected outcome

Submission will pass:

- OpenEnv compliance
- structured logging requirement
- 3 task requirement
- reproducibility requirement
- runtime constraint
- docker build requirement
- HF space endpoint validation

---