NANInithin Claude Opus 4.8 commited on
Commit
7bb583b
·
1 Parent(s): 4b5163f

feat(training): LoRA fine-tune pipeline for Nemotron 3 Nano 4B on Modal

Browse files

Adds training/ — an end-to-end pipeline to fine-tune nvidia/NVIDIA-Nemotron-3-Nano-4B
on the CityQuest game dataset and ship it as a GGUF:

- prepare_dataset.py + convert_to_game_schema.py: build serve-matched SFT prompts
(build_generation_prompt + leave-one-out retrieval) with targets converted to the
app's game_schema.json contract; cached Wikipedia city context.
- train_modal.py: transformers + PEFT LoRA on a Modal A100 (native nemotron_h with
compiled mamba-ssm/causal-conv1d kernels), checkpoint/resume across preemption,
merge, GGUF Q4_K_M convert (forced dense path), upload to HF; plus finalize /
convert_from_merged / evaluate resume + eval entrypoints.
- eval_gguf.py: schema-pass evaluation harness.
- README.md: run instructions.

Uploaded model: NANI-Nithin/CityQuest-Nemotron-3-Nano-4B-GGUF

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

training/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Generated SFT data — regenerate with `python training/prepare_dataset.py`
2
+ data/*.jsonl
3
+ __pycache__/
4
+ # Modal-side outputs (live in Modal volumes / HF, not git)
5
+ outputs/
training/README.md ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CityQuest — Fine-tuning Nemotron 3 Nano 4B
2
+
3
+ Fine-tunes `nvidia/NVIDIA-Nemotron-3-Nano-4B-BF16` (loaded directly from Hugging Face
4
+ with native `transformers` + PEFT — no Unsloth, which doesn't support this brand-new
5
+ `nemotron_h` hybrid-Mamba arch) on the CityQuest game dataset so it natively emits
6
+ games in the app's `game_schema.json` contract, then ships a GGUF Q4_K_M that drops
7
+ into `app/services/generator.py`.
8
+
9
+ ## Pipeline
10
+
11
+ ```
12
+ app/data/<game>/dataset.json
13
+ │ prepare_dataset.py (convert → game_schema, serve-matched prompts, LOO retrieval)
14
+ ▼
15
+ training/data/{train,val}.jsonl
16
+ │ train_modal.py (Unsloth LoRA on A100 → merge → GGUF Q4_K_M → HF upload)
17
+ ▼
18
+ HF: NANI-Nithin/CityQuest-Nemotron-3-Nano-4B-GGUF
19
+ │ eval_gguf.py (schema-pass rate vs baseline) → swap generator.py constants
20
+ ▼
21
+ app serves the fine-tuned model
22
+ ```
23
+
24
+ ## 1. Prepare data (local)
25
+
26
+ ```bash
27
+ python training/prepare_dataset.py # fetches + caches city context (20 cities)
28
+ # or: python training/prepare_dataset.py --no-city-context # offline / faster
29
+ ```
30
+
31
+ Writes `training/data/train.jsonl` and `val.jsonl`. Every target is validated against
32
+ `app/schemas/game_schema.json`; prompts are built with the real
33
+ `build_generation_prompt` so train == serve.
34
+
35
+ ## 2. One-time Modal + HF setup
36
+
37
+ ```bash
38
+ pip install modal
39
+ modal token new # browser auth
40
+ # HF write token from https://huggingface.co/settings/tokens
41
+ modal secret create huggingface HF_TOKEN=hf_xxx
42
+ ```
43
+
44
+ ## 3. Train + upload + evaluate (Modal A100, ~30–60 min)
45
+
46
+ ```bash
47
+ modal run training/train_modal.py::main
48
+ ```
49
+
50
+ This loads the base from HF (native transformers, bf16), trains LoRA (router & lm_head
51
+ excluded), merges to 16-bit, converts to GGUF Q4_K_M via llama.cpp, uploads to
52
+ `NANI-Nithin/CityQuest-Nemotron-3-Nano-4B-GGUF`, then **evaluates** the fine-tuned
53
+ model *and* the stock baseline on the val set and prints a swap gate
54
+ (`fine-tuned >= baseline`).
55
+
56
+ Tunables live at the top of `train_modal.py` (epochs, LoRA rank, batch, lr).
57
+
58
+ ## 4. Evaluate without retraining
59
+
60
+ Evaluation runs on a Modal GPU (the dev Codespace has no llama.cpp), so no local
61
+ runtime is needed:
62
+
63
+ ```bash
64
+ # fine-tuned (defaults to the HF repo above)
65
+ modal run training/train_modal.py::eval_only
66
+ # baseline
67
+ modal run training/train_modal.py::eval_only \
68
+ --repo nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF \
69
+ --file NVIDIA-Nemotron3-Nano-4B-Q4_K_M.gguf
70
+ ```
71
+
72
+ Reports JSON-parse and schema-pass rates. Proceed to the swap only if
73
+ fine-tuned ≥ baseline. (`training/eval_gguf.py` is the equivalent standalone
74
+ script for any environment that *does* have llama.cpp installed, e.g. the HF Space.)
75
+
76
+ ## 5. Swap into the app
77
+
78
+ In `app/services/generator.py`:
79
+
80
+ ```python
81
+ NEMOTRON_MODEL_ID = "NANI-Nithin/CityQuest-Nemotron-3-Nano-4B-GGUF"
82
+ NEMOTRON_GGUF_FILE = "CityQuest-Nemotron-3-Nano-4B-Q4_K_M.gguf"
83
+ ```
84
+
85
+ `story.py` imports these constants, so it follows automatically. Then:
86
+
87
+ ```bash
88
+ python test_generation_gguf.py
89
+ ```
90
+
91
+ ## Files
92
+
93
+ | File | Purpose |
94
+ |------|---------|
95
+ | `convert_to_game_schema.py` | dataset output → `game_schema.json` shape |
96
+ | `prepare_dataset.py` | build chat SFT JSONL (serve-matched prompts) |
97
+ | `requirements-train.txt` | Modal image deps (not app serve deps) |
98
+ | `train_modal.py` | Modal LoRA training + GGUF + HF upload |
99
+ | `eval_gguf.py` | schema-pass evaluation on the val set |
100
+ | `data/` , `city_context_cache.json` | generated artifacts |
training/city_context_cache.json ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokyo": {
3
+ "landmarks": [
4
+ "Tokyo Skytree is the world's tallest tower.",
5
+ "Mary's Cathedral (1967), and the Tokyo Metropolitan Government Building (1991).",
6
+ "The Nezu Shrine and Gokokuji were built by the fifth shogun Tsunayoshi Tokugawa in the late 1600s.",
7
+ "By 1990, the estimated value of the Imperial Palace surpassed that of the entire state of California.",
8
+ "The deadliest night of the war came on March 9–10, 1945, the night of the American \"Operation Meetinghouse\" raid.",
9
+ "As of 2025, Tokyo is home to 26 of the world's 500 largest companies, as listed in the annual Fortune Global 500.",
10
+ "After Dōkan was assassinated in 1486, the Ohgigayatsu branch of the Uesugi clan took control of the castle and the surrounding area.",
11
+ "Recent projects include Ebisu Garden Place, Tennōzu Isle, Shiodome, Roppongi Hills, Shinagawa, and the Marunouchi side of Tokyo Station.",
12
+ "Kisho Kurokawa was also active in the city, and his works there include the National Art Center (2005) and the Nakagin Capsule Tower (1972).",
13
+ "The Imperial Diet, the national legislature of the country, was established in Tokyo in 1889, and it has ever since been operating in the city."
14
+ ],
15
+ "districts": [
16
+ "Kasumigaseki"
17
+ ],
18
+ "parks": [
19
+ "Ueno Park",
20
+ "Yoyogi Park",
21
+ "Ebisu Garden",
22
+ "National Park",
23
+ "Hyakkaen Garden"
24
+ ],
25
+ "description": "Tokyo, officially the Tokyo Metropolis, is the capital and most populous city of Japan. The population of the city proper was over 14 million as of 2023. The Greater Tokyo Area, which includes Tokyo and parts of six neighboring prefectures, is the third-most populous metropolitan area in the world, with 33 million residents as of 2025.\nLying at the head of Tokyo Bay, Tokyo is part of the Kantō region, on the central coast of Honshu, Japan's largest island. It is Japan's economic center and the seat of the Japanese government and the Emperor of Japan. The Tokyo Metropolitan Government administe"
26
+ },
27
+ "bangalore": {
28
+ "landmarks": [
29
+ "The city is known as India's \"Garden City\", due to its parks and greenery.",
30
+ "Bengaluru has the country's fourth largest fast-moving consumer goods market.",
31
+ "Kempe Gowda also built the temple at Basavanagudi, and expanded other temples.",
32
+ "His successor, Kempe Gowda II, built four towers to mark the boundary of the town.",
33
+ "Yakshagana, a theatre art indigenous to coastal Karnataka is often played in town halls.",
34
+ "It hosted 87 Fortune 500 companies, the fifth highest number amongst the cities in India.",
35
+ "Within the fort, the town was divided into smaller divisions, each called a pētē (Kannada pronunciation: ).",
36
+ "Several art galleries including the government-established National Gallery of Modern Art emerged in the 1990s.",
37
+ "The kingdom later passed to Hyder Ali's son Tipu Sultan, and the Lal Bagh garden was established around 1760 CE.",
38
+ "The Indian Cartoon Gallery organised by the Indian Institute of Cartoonists, conducts periodic cartoon exhibitions."
39
+ ],
40
+ "districts": [
41
+ "Kodagu"
42
+ ],
43
+ "parks": [
44
+ "Freedom Park",
45
+ "The Cubbon Park",
46
+ "Bagmane Tech Park",
47
+ "International Tech Park",
48
+ "Software Technology Park"
49
+ ],
50
+ "description": "Bengaluru, also known as Bangalore (its official name until 1 November 2014), is the capital and largest city of the southern Indian state of Karnataka. As per the 2011 census, the city had a population of 8.4 million, making it the third most populous city in India and the most populous in South India. The Bengaluru metropolitan area had a population of around 8.5 million, making it the fifth most populous urban agglomeration in the country. It is located towards the southern end of the Deccan Plateau, at an altitude of 900 m (3,000 ft) above sea level. The city is known as India's \"Garden Ci"
51
+ },
52
+ "berlin": {
53
+ "landmarks": [
54
+ "Peter's Basilica in Rome.",
55
+ "Berlin has numerous museums, galleries, and libraries.",
56
+ "Hedwig's Cathedral is Berlin's Roman Catholic cathedral.",
57
+ "The Berlin Zoological Garden is the most visited zoo in Europe.",
58
+ "The church was destroyed in the Second World War and left in ruins.",
59
+ "The office of the Governing Mayor is in the Rotes Rathaus (Red City Hall).",
60
+ "West of the center, Bellevue Palace is the residence of the German President.",
61
+ "Berlin hosted the 1936 Summer Olympics for which the Olympic stadium was built.",
62
+ "Its main exhibition area covers more than 160,000 square meters (1,722,226 sq ft).",
63
+ "The Memorial to the Murdered Jews of Europe, a Holocaust memorial, is to the north."
64
+ ],
65
+ "districts": [],
66
+ "parks": [
67
+ "Business Park",
68
+ "Treptower Park",
69
+ "Botanical Garden",
70
+ "The Berlin Zoological Garden"
71
+ ],
72
+ "description": "Berlin is the capital of Germany as well as its largest city by both area and population. With 3.7 million inhabitants, it has the highest population within its city limits of any city in the European Union. The city is also one of the states of Germany, being the third-smallest state in the country by area. Berlin is surrounded by the state of Brandenburg, bordering Brandenburg's capital Potsdam to the southwest. The urban area of Berlin has a population of over 5 million, making it the most populous in Germany. The Berlin-Brandenburg capital region has around 6 million inhabitants and is Ger"
73
+ },
74
+ "copenhagen": {
75
+ "landmarks": [
76
+ "=== Parks, gardens and zoo ===",
77
+ "Clemens Church had been built.",
78
+ "Later, towers were built along the city wall.",
79
+ "Both ports are operated by Copenhagen Malmö Port (CMP).",
80
+ "The Øresund Bridge connects the two cities by rail and road.",
81
+ "Intended as a fortified trading centre, it ultimately became part of Copenhagen.",
82
+ "The national library's Black Diamond building on the waterfront was completed in 1999.",
83
+ "In 1733, work began on the royal residence of Christiansborg Palace, completed in 1745.",
84
+ "In Klampenborg, about 10 kilometres (6.2 mi) from downtown Copenhagen, is Bellevue Beach.",
85
+ "The beaches are supplemented by a system of Harbour Baths along the Copenhagen waterfront."
86
+ ],
87
+ "districts": [],
88
+ "parks": [
89
+ "Tivoli Gardens",
90
+ "Botanical Gardens",
91
+ "The Tivoli Gardens",
92
+ "Frederiksberg Gardens",
93
+ "Rosenborg Castle Gardens"
94
+ ],
95
+ "description": "Copenhagen (Danish: København [kʰøpm̩ˈhɑwˀn] ) is the capital and most populous city of both the country of Denmark and the wider Kingdom of Denmark, with a population of 671,714 people in the municipality and 1.4 million in the urban area. The city is situated mainly on the island of Zealand (Sjælland), with a smaller part on the island of Amager. Copenhagen is separated from Malmö, Sweden, by the Øresund strait. The Øresund Bridge connects the two cities by rail and road.\nSettled as a Viking fishing village in the 10th century in the vicinity of what is now Gammel Strand, Copenhagen became t"
96
+ },
97
+ "auckland": {
98
+ "landmarks": [
99
+ "The Auckland Botanic Gardens are further south, in Manurewa.",
100
+ "Major markets include those held in Ōtara and Avondale on weekend mornings.",
101
+ "It has an advanced market economy with strengths in finance, commerce, and tourism.",
102
+ "The west coast has popular surf beaches such as Piha, Muriwai and Te Henga (Bethells Beach).",
103
+ "During the New Zealand wars many fencibles and soldiers were stationed in and around Auckland.",
104
+ "Immigration to New Zealand is heavily concentrated towards Auckland (partly for job market reasons).",
105
+ "Queen Street, Britomart, Ponsonby Road, Karangahape Road, Newmarket and Parnell are major retail areas.",
106
+ "Ngāti Whātua sought British protection from Ngāpuhi as well as a reciprocal relationship with the Crown and the Church.",
107
+ "Many Auckland beaches are patrolled by surf lifesaving clubs, such as Piha Surf Life Saving Club the home of Piha Rescue.",
108
+ "The Viaduct Basin, on the western edge of the CBD, hosted three America's Cup challenges (2000 Cup, 2003 Cup and 2021 Cup)."
109
+ ],
110
+ "districts": [],
111
+ "parks": [
112
+ "Eden Park",
113
+ "Myers Park",
114
+ "Sylvia Park",
115
+ "Albert Park",
116
+ "Western Park"
117
+ ],
118
+ "description": "Auckland is a large metropolitan city in the North Island of New Zealand. It has an urban population of about 1,547,200 (June 2025). It is located in the greater Auckland Region, the area governed by Auckland Council, which includes outlying rural areas and the islands of the Hauraki Gulf, and which has a total population of 1,816,000 as of June 2025. It is the most populous city of New Zealand and the fifth-most populous city in Oceania.\nThe city lies between the Hauraki Gulf to the east, the Hunua Ranges to the south-east, the Manukau Harbour to the south-west, and the Waitākere Ranges and s"
119
+ },
120
+ "seoul": {
121
+ "landmarks": [
122
+ "'10 Ris around the fortress').",
123
+ "The Yongsan Electronics Market is the largest electronics market in Asia.",
124
+ "The Fortress Wall surrounding Hanyang was partially finished around 1396.",
125
+ "Wholesale markets include Noryangjin Fisheries Wholesale Market and Garak Market.",
126
+ "In 2017 the Seoullo 7017 Skypark opened, spanning diagonally overtop Seoul Station.",
127
+ "Hwanghak-dong Flea Market and Janganpyeong Antique Market also offer antique products.",
128
+ "The largest wholesale and retail market in South Korea, the Dongdaemun Market, is located in Seoul.",
129
+ "The 2nd World trade trade center is being planned at Seoul Olympic stadium complex as MICE HUB by Seoul.",
130
+ "During its early construction stages, some major palaces, including Gyeongbokgung, were finished in 1395.",
131
+ "The nearby Namdaemun Market, named after the Namdaemun Gate, is the oldest continually running market in Seoul."
132
+ ],
133
+ "districts": [
134
+ "Administrative"
135
+ ],
136
+ "parks": [
137
+ "Namsan Park",
138
+ "Olympic Park",
139
+ "Banpo Hangang Park",
140
+ "Nanji Hangang Park",
141
+ "Seoul Olympic Park"
142
+ ],
143
+ "description": "Seoul, officially Seoul Special Metropolitan City, is the capital and largest city of South Korea, and the largest city in the whole of Korea. The broader Seoul Metropolitan Area, encompassing Seoul, Gyeonggi Province and Incheon, emerged as the world's sixth largest metropolitan economy in 2022, behind New York, Tokyo, Los Angeles, Paris, and London, and hosts more than half of South Korea's population. Although Seoul's population peaked at over 10 million, it has gradually decreased since 2014, standing at about 9.6 million residents as of 2024. \nSeoul's history traces back to 18 BC when it"
144
+ },
145
+ "paris": {
146
+ "landmarks": [
147
+ "The President of the French Republic resides at the Élysée Palace.",
148
+ "Fortification of the Île de la Cité failed to avert sacking by Vikings in 845.",
149
+ "It became a prosperous city with a forum, baths, temples, theatres, and an amphitheatre.",
150
+ "Louis XVI and the royal family were brought to Paris and incarcerated in the Tuileries Palace.",
151
+ "Station F is a business incubator for startups, noted as the world's largest startup facility.",
152
+ "He built five new bridges, a new chapel for the College of Sorbonne, and a palace for himself, the Palais-Cardinal.",
153
+ "In 2021, the top French companies listed in the Fortune Global 500 all have their headquarters in the Paris Region.",
154
+ "2,885 were living in the streets or parks, 298 in train and metro stations, and 756 in other forms of temporary shelter.",
155
+ "The property of the aristocracy and the church was nationalised, and the city's churches were closed, sold, or demolished.",
156
+ "Due to the Parisian uprisings during the Fronde civil war, Louis XIV moved his court to a new palace, Versailles, in 1682."
157
+ ],
158
+ "districts": [
159
+ "La Défense"
160
+ ],
161
+ "parks": [
162
+ "Tuileries Garden",
163
+ "Luxembourg Garden"
164
+ ],
165
+ "description": "Paris is the capital and largest city of France, with an estimated city population of 2.04 million in an area of 105.4 km2 (40.7 sq mi), and a metropolitan population of 13.2 million as of January 2026. Located on the river Seine in the centre of the Île-de-France region, it is the largest metropolitan area and fourth-most populous city in the European Union (EU). Nicknamed the \"City of Light\", partly because of its role in the Age of Enlightenment, Paris has been one of the world's major centres of finance, diplomacy, commerce, culture, fashion, and gastronomy since the 17th century.\nAdminist"
166
+ },
167
+ "buenos aires": {
168
+ "landmarks": [
169
+ "The statue was placed in the abbey.",
170
+ "Lastly, to the northwest, is City Hall.",
171
+ "Plaza San Martín is a park located in the city's neighborhood of Retiro.",
172
+ "Buenos Aires Japanese Gardens is the largest of its type in the world, outside Japan.",
173
+ "Buenos Aires was conceived around the Plaza de Mayo, the colony's administrative center.",
174
+ "Thays designed the Zoological Gardens, the Botanical Gardens, the adjoining Plaza Italia and the Rose Garden.",
175
+ "In 1335, King Alfonso the Gentle donated the church to the Mercedarians, who built an abbey that stands to this day.",
176
+ "To the east of the square is the Casa Rosada, the official seat of the executive branch of the government of Argentina.",
177
+ "Botanical Gardens, designed by French architect and landscape designer Carlos Thays, the garden was inaugurated on 7 September 1898.",
178
+ "Completed in 1967, the gardens were inaugurated on the occasion of a State visit to Argentina by Crown Prince Akihito and Princess Michiko of Japan."
179
+ ],
180
+ "districts": [
181
+ "San Telmo",
182
+ "Puerto Madero"
183
+ ],
184
+ "parks": [
185
+ "Rose Garden",
186
+ "Botanical Gardens",
187
+ "Zoological Gardens",
188
+ "Buenos Aires Japanese Gardens",
189
+ "Buenos Aires Ecological Reserve"
190
+ ],
191
+ "description": "Buenos Aires, officially the Autonomous City of Buenos Aires, is the capital and largest city of Argentina. It is located on the southwest of the Río de la Plata. Buenos Aires is classified as an Alpha− global city, according to the GaWC 2024 ranking. The city proper has a population of 3.1 million and its urban area has a population of 16.7 million, making it the 21st most populous metropolitan area in the world.\nIt is known for its preserved eclectic European architecture and rich cultural life. It is a multicultural city that is home to multiple ethnic and religious groups, contributing to"
192
+ },
193
+ "cape town": {
194
+ "landmarks": [
195
+ "Most places of worship in Cape Town are Christian churches and cathedrals.",
196
+ "Other religious sites in the city include Hindu and Buddhist temples and centres.",
197
+ "Temple Israel (Cape Town Progressive Jewish Congregation) also has three temples in the city.",
198
+ "However, naturally, due to the size of Cape Town's population and the value of its real estate market, significant rates are raised each year.",
199
+ "Nobel Square in the Victoria & Alfred Waterfront features statues of South Africa's four Nobel Peace Prize winners: Albert Luthuli, Desmond Tutu, F.",
200
+ "Cape Town reached first place in the 2019 iNaturalist City Nature Challenge in two out of the three categories: Most Observations, and Most Species.",
201
+ "This initiative has transformed public spaces such as Greenmarket Square, Company's Garden, and St George's Mall, attracting both locals and tourists.",
202
+ "These include Kirstenbosch National Botanical Garden, which contains 5 of South Africa's 6 biomes, and displays many plants native to the Cape region.",
203
+ "This has resulted in a number of mosques and other Muslim religious sites spread across the city, such as the Auwal Mosque - South Africa's first mosque.",
204
+ "The metropolitan area has a long coastline on the Atlantic Ocean, which includes a northern section in the West Beach region, as well as the False Bay area in the south."
205
+ ],
206
+ "districts": [
207
+ "Stellenbosch"
208
+ ],
209
+ "parks": [
210
+ "Grassy Park",
211
+ "Acacia Park",
212
+ "Urban Forest",
213
+ "Old Mutual Park",
214
+ "Newlands Forest"
215
+ ],
216
+ "description": "Cape Town is the legislative capital of South Africa. It is the country's oldest city and the seat of the Parliament of South Africa. Cape Town is the country's second-largest city by population, after Johannesburg, and the largest city in the Western Cape. The city is part of the City of Cape Town metropolitan municipality.\nThe city is known for its harbour, its natural setting in the Cape Floristic Region, and for landmarks such as Table Mountain and Cape Point. Located on the shore of Table Bay, the City Bowl area of Cape Town, which contains its central business district (CBD), is the olde"
217
+ },
218
+ "lagos": {
219
+ "landmarks": [
220
+ "The new fruit market comprises 1,004 shop units.",
221
+ "Three major bridges join the Island to the Mainland.",
222
+ "\"The fertiliser market is a seller's market,\" company owner Dangote raves.",
223
+ "Andela trains software engineers and places them in the Nigerian labour market.",
224
+ "It borders the Idumota and Balogun markets and houses major Banking institutions.",
225
+ "The Ikoyi link bridge links Ikoyi and Lekki Phase 1, both of which are part of the Island.",
226
+ "Lagos also has a number of private beach resorts, including the Inagbe Grand Beach Resort.",
227
+ "On its seashore along the Atlantic front, there is an environmentally reconstructed Bar Beach.",
228
+ "The site is 1.2 million square meters big and the construction is expected to be finished in 2024.",
229
+ "Lagos National Stadium has hosted various international sports events, such as the 1980 African Cup of Nations."
230
+ ],
231
+ "districts": [
232
+ "Yaba",
233
+ "This",
234
+ "Island"
235
+ ],
236
+ "parks": [
237
+ "Freedom Park",
238
+ "Lufasi Nature Park",
239
+ "Ndubuisi Kanu Park",
240
+ "Food Logistics Park"
241
+ ],
242
+ "description": "Lagos File: ( LAY-goss; Yoruba: Èkó [èkó]), or Lagos City, is a large metropolitan port city in southwestern Nigeria. As of November 2025, the size of the city's population has been estimated to be between 17 and 21 million residents, making Lagos the largest city in Nigeria, the most populous urban area on the African continent, and one of the fastest-growing megacities in the world. Lagos was the national capital of Nigeria until the government's December 1991 decision to relocate its capital to Abuja, in the centre of the country. Apart from serving as a major African financial center, Lag"
243
+ },
244
+ "nairobi": {
245
+ "landmarks": [
246
+ "== Parks and gardens ==",
247
+ "It is now the site of a memorial park.",
248
+ "It is a 33-storey tower 163 meters high.",
249
+ "This stadium is primarily used for football.",
250
+ "Hotel towers are also being erected in the city.",
251
+ "The hotel tower will be operated by Marriot group.",
252
+ "The city square is also located within the perimeter.",
253
+ "It had the largest halls in eastern and central Africa.",
254
+ "Completed in 1983, the stadium has a capacity of 30,000.",
255
+ "The stadium has seats in the VIP section and regular stands."
256
+ ],
257
+ "districts": [],
258
+ "parks": [
259
+ "Golf Park",
260
+ "City Park",
261
+ "View Park",
262
+ "Hill Park",
263
+ "Uhuru Park"
264
+ ],
265
+ "description": "Nairobi ( ny-ROH-bee) is the capital and largest city of Kenya, located in the south-central part of the country. As of 2024, it has a population of 4.8 million and a metropolitan population of 5.7 million, making it the 8th most populous city in Africa. Nicknamed the \"Green City under the Sun\", Nairobi is uniquely notable for being the only capital city in the world that hosts a national park within its boundaries. Its name originates from the Maasai phrase Enkare Nyirobi, meaning \"place of cool waters\".\nAs the national capital, Nairobi is home to the Kenyan Parliament Buildings, the State H"
266
+ },
267
+ "lisbon": {
268
+ "landmarks": [
269
+ "To the west of the gardens lies the Centro Cultural de Belém.",
270
+ "Amongst the palaces found in the neighbourhood the most notable are:",
271
+ "Its name, derived from the Arabic Al-hamma, means fountains or baths.",
272
+ "All mosques were either destroyed or altered and converted into churches.",
273
+ "The ornate, late 18th-century Estrela Basilica is the main attraction of this district.",
274
+ "The style is similar to that of the Palace-Convent of Mafra, late baroque and neoclassical.",
275
+ "The façade has twin bell towers and includes statues of saints and some allegorical figures.",
276
+ "The Chiado is also an important cultural area, with several museums and theatres, including the opera.",
277
+ "The inauguration of the bridge over the Tagus allowed a rapid connection between both sides of the river.",
278
+ "In the heart of Belém is the Praça do Império: gardens centred upon a large fountain, laid out during World War II."
279
+ ],
280
+ "districts": [
281
+ "Baixa",
282
+ "Alfama",
283
+ "Chiado",
284
+ "Moorish"
285
+ ],
286
+ "parks": [
287
+ "Estrela Park",
288
+ "Monsanto Forest Park"
289
+ ],
290
+ "description": "Lisbon ( LIZ-bən; Portuguese: Lisboa [liʒˈβoɐ] ) is the capital and most populous city of Portugal, with an estimated population of 575,739 as of 2024, within its administrative limits and 3,028,000 within the metropolis, as of 2025. The city lies in the western portion of the Iberian Peninsula, on the northern shore of the River Tagus. The western portion of its metro area, the Portuguese Riviera, hosts the westernmost point of Continental Europe, culminating at Cabo da Roca.\nLisbon is one of the oldest cities in the world and the second-oldest European capital city (after Athens), predating"
291
+ },
292
+ "amsterdam": {
293
+ "landmarks": [
294
+ "It is near Dam Square in the city centre.",
295
+ "around Amsterdam Sloterdijk railway station.",
296
+ "Herring had demand in markets all around Europe.",
297
+ "The city has many open squares (plein in Dutch).",
298
+ "The city became the staple market of Europe for bulk cargo.",
299
+ "Amsterdam's tallest building, the Rembrandt Tower, is located here.",
300
+ "Amsterdam has many parks, open spaces, and squares throughout the city.",
301
+ "The new city hall was built on the almost completely demolished Waterlooplein.",
302
+ "In the park is an open-air theatre, a playground, and several horeca facilities.",
303
+ "The prehistoric IJ was a shallow and quiet stream in peatland behind beach ridges."
304
+ ],
305
+ "districts": [
306
+ "Whole",
307
+ "Jewish",
308
+ "Jordaan",
309
+ "Plantage"
310
+ ],
311
+ "parks": [
312
+ "Science Park",
313
+ "Central Park",
314
+ "Amsterdam Forest"
315
+ ],
316
+ "description": "Amsterdam (Dutch: [ˌɑmstərˈdɑm] ; lit. 'Dam in the Amstel') is the capital and largest city of the Netherlands. It has a population of 933,680 in June 2024 within the city proper, 1,457,018 in the urban area and 2,480,394 in the metropolitan area. Located in the Dutch province of North Holland, Amsterdam is colloquially referred to as the \"Venice of the North\", for its large number of canals, now a UNESCO World Heritage Site.\nAmsterdam was founded at the mouth of the Amstel River, which was dammed to control flooding. Originally a small fishing village in the 12th century, Amsterdam became a m"
317
+ },
318
+ "bogota": {
319
+ "landmarks": [
320
+ "The National Museum was founded.",
321
+ "In La Candelaria, there are many museums, including the Botero Museum and the Gold Museum.",
322
+ "In other words, the city grew in area adding new square blocks but kept the same urban fabric.",
323
+ "There is also Usaquen, a colonial landmark where brunch and a flea market on Sundays is a traditional activity.",
324
+ "Thereafter, the empty plazas of the colonial ages turned into ornamented plazas with plenty of trees and civic statues.",
325
+ "The names of colonial streets were changed to numbers and the name of plazas were changed to the founding fathers of Colombia.",
326
+ "For instance, the first civil statue placed in a plaza in Colombia was the figure of Bolivar, the main founding father of Colombia.",
327
+ "The city's urban shape remained the same in the 19th century as the 1557 urban landscape as a checkerboard with the Plaza as its core.",
328
+ "Jiménez de Quesada decided to establish a military campament in the area in 1538, in the site today known as the Chorro de Quevedo square.",
329
+ "The square is located in the city's historical center, La Candelaria, which features architecture in Spanish Colonial and Spanish Baroque styles."
330
+ ],
331
+ "districts": [
332
+ "Santa Fe",
333
+ "La Macarena"
334
+ ],
335
+ "parks": [
336
+ "National Park",
337
+ "Santander Park",
338
+ "Jaime Duque Park",
339
+ "The Usaquén Park",
340
+ "Botanical Garden"
341
+ ],
342
+ "description": "Bogotá (, also UK: , US: , Spanish pronunciation: [boɣoˈta] ) is the capital and largest city of Colombia. The city is administered as the Capital District, as well as the capital of, though not politically part of, the surrounding department of Cundinamarca. Bogotá is a territorial entity of the first order, with the same administrative status as the departments of Colombia. It is the main political, economic, administrative, industrial, cultural, aeronautical, technological, scientific, medical, educational and airport center of the country and northern South America.\nBogotá was founded as t"
343
+ },
344
+ "mumbai": {
345
+ "landmarks": [
346
+ "Michael's Church at Mahim (1534), St.",
347
+ "John the Baptist Church at Andheri (1579), St.",
348
+ "As of 2011, the BEST operated 4,608 buses along 390 routes.",
349
+ "Ride hailing services Ola, Rapido, and Uber operate in the city.",
350
+ "Andrew's Church at Bandra (1580), and Gloria Church at Byculla (1632).",
351
+ "Ferry services are operated by government agencies and private partners.",
352
+ "The Portuguese Franciscans and Jesuits built churches in the city, such as the St.",
353
+ "The city is home to many of India's conglomerates and five of the Fortune Global 500 companies.",
354
+ "The public bus transport system is operated by Brihanmumbai Electric Supply and Transport (BEST).",
355
+ "They also built several fortifications including the Bombay Castle, Castella de Aguada, and Madh Fort."
356
+ ],
357
+ "districts": [
358
+ "Thane",
359
+ "Raigad",
360
+ "Mumbai Suburban"
361
+ ],
362
+ "parks": [
363
+ "Victoria Gardens",
364
+ "Borivali National Park",
365
+ "The Sanjay Gandhi National Park"
366
+ ],
367
+ "description": "Mumbai ( muum-BY; Marathi: Mumbaī, pronounced [ˈmumbəi] ), also known as Bombay ( bom-BAY; its official name until 1995), is the capital city of the Indian state of Maharashtra. Mumbai is the financial capital and the most populous city proper of India, with an estimated population of 12.5 million (1.25 crore). Mumbai is the centre of the Mumbai Metropolitan Region, which is among the most populous metropolitan areas in the world with a population of over 23 million (2.3 crore). Mumbai lies on the Konkan coast on the west coast of India and has a deep natural harbour. In 2008, Mumbai was named"
368
+ },
369
+ "istanbul": {
370
+ "landmarks": [
371
+ "Hagia Sophia was converted to a Catholic church in 1204.",
372
+ "Its area of 5,461 square kilometers (2,109 mi2) is coterminous with Istanbul Province.",
373
+ "Money could not protect the rich from all the discomforts and harsher sides of Istanbul.",
374
+ "The modernization efforts were not enough to forestall the decline of the Ottoman Empire.",
375
+ "Another park, Fethi Paşa Korusu, is on a hillside adjacent to the Bosphorus Bridge in Anatolia, opposite Yıldız Palace in Europe.",
376
+ "The former village of Ortaköy is within Beşiktaş and gives its name to the Ortaköy Mosque on the Bosporus, near the Bosporus Bridge.",
377
+ "Large sections of Caddebostan sit on areas of landfill, increasing the total area of the city to 5,343 square kilometers (2,063 sq mi).",
378
+ "The largest palace, Topkapı, includes a diverse array of architectural styles, from Baroque inside the Harem, to its Neoclassical Enderûn Library.",
379
+ "Over the next four centuries, the Ottomans proceeded to make an indelible impression on the skyline of Istanbul, building towering mosques and ornate palaces.",
380
+ "Bridges across the Golden Horn were constructed during this period, and Constantinople was connected to the rest of the European railway network in the 1880s."
381
+ ],
382
+ "districts": [
383
+ "The Fatih"
384
+ ],
385
+ "parks": [
386
+ "Gezi Park",
387
+ "Rams Park",
388
+ "Emirgan Park",
389
+ "Gülhane Park",
390
+ "Istanbul Park"
391
+ ],
392
+ "description": "Istanbul is the largest city in Turkey, constituting the country's economic, cultural, and historical center. With a population of over 15 million, it is home to 18% of the population of Turkey. Istanbul is among the largest cities in Europe and in the world by population. It is a city on two continents; about two-thirds of its population live in Europe and the rest in Asia. Istanbul straddles the Bosphorus – one of the world's busiest waterways – in northwestern Turkey, between the Sea of Marmara and the Black Sea. Its area of 5,461 square kilometers (2,109 mi2) is coterminous with Istanbul P"
393
+ },
394
+ "marrakech": {
395
+ "landmarks": [
396
+ "=== Palaces and Riads ===",
397
+ "1163–1184) began the Agdal Gardens.",
398
+ "This second mosque is the structure that stands today.",
399
+ "It is located next to the south wall of the Kasbah Mosque.",
400
+ "The Dar Si Said Museum is to the north of the Bahia Palace.",
401
+ "It is one of the only major Marinid-era monuments in the city.",
402
+ "Much of this trade can be found in the medina and adjacent squares.",
403
+ "The mosque was founded in 1147 by the Almohad caliph Abd al-Mu'min.",
404
+ "The city is home to a number of gardens, both historical and modern.",
405
+ "Churchill used to relax within the gardens of the hotel and paint there."
406
+ ],
407
+ "districts": [
408
+ "Jewish",
409
+ "Kasbah"
410
+ ],
411
+ "parks": [
412
+ "Agdal Gardens",
413
+ "Menara Gardens",
414
+ "The Secret Garden",
415
+ "The Agdal Gardens",
416
+ "Koutoubia Gardens"
417
+ ],
418
+ "description": "Marrakesh or Marrakech is the fourth-largest city in Morocco. It is one of the four imperial cities of Morocco and is the capital of the Marrakesh-Safi region. The city lies west of the foothills of the Atlas Mountains.\nThe city was founded circa 1070 by Abu Bakr ibn Umar as the capital of the Almoravid dynasty. The Almoravids established the first major structures in the city and shaped its layout for centuries to come. The red walls of the city, built by Ali ibn Yusuf in 1122–1123, and various buildings constructed in red sandstone afterwards, have given the city the nickname of the \"Red Cit"
419
+ },
420
+ "sydney": {
421
+ "landmarks": [
422
+ "One journalist wrote, \"Golden beaches.",
423
+ "Elaborate coffee palaces and hotels were erected.",
424
+ "Mortimer Lewis designed the Australian Museum in 1857.",
425
+ "This makes them the oldest botanic garden in Australia.",
426
+ "The most notable architectural feat of this period is the Harbour Bridge.",
427
+ "Sydney Zoo, opened in 2019, is another prominent zoo situated in Bungaribee.",
428
+ "The neo-Classical and French Second Empire style Town Hall was completed in 1889.",
429
+ "Jørn Utzon was awarded the Pritzker Prize in 2003 for his work on the Opera House.",
430
+ "The tallest structure is Sydney Tower, designed by Donald Crone and completed in 1981.",
431
+ "The Sydney Basin bioregion includes coastal features of cliffs, beaches, and estuaries."
432
+ ],
433
+ "districts": [
434
+ "Hills",
435
+ "The Hills",
436
+ "The Southern"
437
+ ],
438
+ "parks": [
439
+ "Ruth Park",
440
+ "Hyde Park",
441
+ "Luna Park",
442
+ "Oran Park",
443
+ "Moore Park"
444
+ ],
445
+ "description": "Sydney is the capital city of the state of New South Wales, and the most populous city in Australia. Located on Australia's east coast, the metropolis surrounds Sydney Harbour and extends about 80 kilometres (50 mi) from the Pacific Ocean in the east to the Blue Mountains in the west, and about 80 kilometres (50 mi) from Ku-ring-gai Chase National Park and the Hawkesbury River in the north and north-west, to the Royal National Park and Macarthur in the south and south-west. Greater Sydney consists of 658 suburbs, spread across 33 local government areas. Residents of the city are colloquially k"
446
+ },
447
+ "new york city": {
448
+ "landmarks": [
449
+ "Brooklyn is also home to Fort Hamilton, the U.S.",
450
+ "The year 2000 was celebrated with fanfare in Times Square.",
451
+ "The city's total area is 468.484 square miles (1,213.37 km2).",
452
+ "They are joined in the harbor by Governors Island National Monument.",
453
+ "county for the average home price per square foot, and produces the highest U.S.",
454
+ "military's only active duty installation within New York City, aside from Coast Guard operations.",
455
+ "New York City remains the largest global center for trading in public equity and debt capital markets.",
456
+ "New York City has over 28,000 acres (110 km2) of municipal parkland and 14 miles (23 km) of public beaches.",
457
+ "Local politics became dominated by Tammany Hall, a political machine supported by Irish and German immigrants.",
458
+ "It is connected to Brooklyn by the Verrazzano–Narrows Bridge, and to Manhattan by way of the free Staten Island Ferry."
459
+ ],
460
+ "districts": [],
461
+ "parks": [
462
+ "Etihad Park",
463
+ "Ditmas Park",
464
+ "Corona Park",
465
+ "Central Park",
466
+ "Battery Park"
467
+ ],
468
+ "description": "New York, often called New York City (NYC), is the most populous city in the United States. It is located at the southern tip of New York State on New York Harbor, one of the world's largest natural harbors. The city comprises five boroughs—Manhattan, Brooklyn, Queens, the Bronx, and Staten Island; each is coextensive with its respective county. It is the geographical and demographic center of both the Northeast megalopolis and the New York metropolitan area, the largest metropolitan area in the United States by both population and urban area. New York is a global center of finance and commer"
469
+ },
470
+ "mexico city": {
471
+ "landmarks": [
472
+ "Mexico City has three zoos.",
473
+ "Chapultepec Zoo, the San Juan de Aragon Zoo and Los Coyotes Zoo.",
474
+ "Quitman, spearheaded the attack against Chapultepec and carried the castle.",
475
+ "Zoo San Juan de Aragon is near the San Juan de Aragon Park in the Gustavo A.",
476
+ "The invasion culminated with the storming of Chapultepec Castle in the city itself.",
477
+ "Chapultepec Zoo is located in the first section of Chapultepec Park in the Miguel Hidalgo.",
478
+ "Cortés put Moctezuma under house arrest at his father's palace, hoping to rule through him.",
479
+ "Zoo Los Coyotes is a 27.68-acre (11.2 ha) zoo located south of Mexico City in the Coyoacan.",
480
+ "In the southeast is the Xochimilco Ecological Park and Plant Market, a World Heritage Site.",
481
+ "The viceroy of Mexico or vice-king lived in the viceregal palace on the main square or Zócalo."
482
+ ],
483
+ "districts": [
484
+ "Ajusco",
485
+ "Polanco",
486
+ "Condesa",
487
+ "Santa Fe"
488
+ ],
489
+ "parks": [
490
+ "Aragon Park",
491
+ "Chapultepec Park",
492
+ "Leones National Park",
493
+ "Xochimilco Ecological Park"
494
+ ],
495
+ "description": "Mexico City is the capital and most populous city of Mexico, as well as the most populous city in North America. It is one of the world's leading cultural and financial centers and, according to the Globalization and World Cities Research Network's 2024 ranking, is classified as an Alpha world city. Located in the Valley of Mexico on the high Mexican Central Plateau, the city sits at an altitude of 2,240 meters (7,350 feet). It is divided into 16 boroughs, or demarcaciones territoriales, which are further subdivided into neighborhoods, or colonias.\nAccording to the 2020 census, Mexico City pro"
496
+ }
497
+ }
training/convert_to_game_schema.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert raw dataset ``output`` objects into the app's ``game_schema.json`` shape.
2
+
3
+ The synthetic datasets under ``app/data/<game>/dataset.json`` store rich,
4
+ game-type-specific outputs (``game_title`` / ``rules{}`` / ``hiding_zones`` /
5
+ ``arena`` / ...). The *running app*, however, only ever consumes the flat,
6
+ ``tasks[]``-based contract defined in ``app/schemas/game_schema.json`` (see
7
+ ``app/services/validator.py`` and the rendering in ``app.py``). ``game_type`` is
8
+ merely stamped onto that flat structure.
9
+
10
+ To fine-tune a drop-in replacement model, every training target must already be
11
+ in ``game_schema.json`` shape, so this module maps each dataset output to it:
12
+
13
+ * scavenger_hunt — direct task→task mapping
14
+ * hide_and_seek — synthesizes tasks[] from ``hiding_zones``
15
+ * tag — synthesizes tasks[] from ``safe_zones`` (+ movement features)
16
+
17
+ The mapping is intentionally deterministic so the produced JSON validates
18
+ against ``game_schema.json`` for every record.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ from typing import Optional
25
+
26
+
27
+ # ── small helpers ────────────────────────────────────────────────────────────
28
+
29
+ def _first_sentence(text: str, limit: int = 160) -> str:
30
+ if not text:
31
+ return ""
32
+ parts = re.split(r"(?<=[.!?])\s+", text.strip())
33
+ out = parts[0] if parts else text
34
+ return out[:limit].strip()
35
+
36
+
37
+ def _short_title(text: str, words: int = 5) -> str:
38
+ if not text:
39
+ return "Explore the area"
40
+ cleaned = re.sub(r"[^A-Za-z0-9 ,.'-]", " ", text).strip()
41
+ return " ".join(cleaned.split()[:words]).rstrip(",.")
42
+
43
+
44
+ def _proof_type_for_task(task: dict) -> str:
45
+ """Map a scavenger task to the game_schema proof_type enum."""
46
+ blob = " ".join(
47
+ str(task.get(k, "")).lower()
48
+ for k in ("task_type", "completion_proof", "title", "description")
49
+ )
50
+ if any(w in blob for w in ("photo", "photograph", "picture", "selfie", "image")):
51
+ return "photo"
52
+ if any(w in blob for w in ("observe", "answer", "count", "identify", "record", "note", "find")):
53
+ return "observation"
54
+ return "text"
55
+
56
+
57
+ def _concealment_points(rating: str) -> int:
58
+ return {"high": 30, "medium": 20, "low": 10}.get((rating or "").lower(), 20)
59
+
60
+
61
+ def _tone_for(game_type: str, theme: str) -> str:
62
+ """Pick a story_seed tone from the enum [playful, cinematic, chaotic, wholesome]."""
63
+ if game_type == "tag":
64
+ return "chaotic"
65
+ if game_type == "hide_and_seek":
66
+ return "playful"
67
+ if (theme or "").lower() in ("history", "urban_exploration", "photography"):
68
+ return "cinematic"
69
+ if (theme or "").lower() in ("nature", "social"):
70
+ return "wholesome"
71
+ return "playful"
72
+
73
+
74
+ def _flatten_rules(rules_obj) -> list[str]:
75
+ """Flatten a rules object/list into a list of human-readable strings."""
76
+ if isinstance(rules_obj, list):
77
+ return [str(r) for r in rules_obj if r]
78
+ if not isinstance(rules_obj, dict):
79
+ return []
80
+ out: list[str] = []
81
+ if rules_obj.get("objective"):
82
+ out.append(f"Objective: {rules_obj['objective']}")
83
+ for key in ("round_structure", "team_rules", "tag_mechanic", "unfreeze_or_revival_rule"):
84
+ if rules_obj.get(key):
85
+ out.append(str(rules_obj[key]))
86
+ if rules_obj.get("win_condition"):
87
+ out.append(f"Win condition: {rules_obj['win_condition']}")
88
+ for cond in rules_obj.get("disqualification_conditions", []) or []:
89
+ out.append(f"Disqualification: {cond}")
90
+ return out
91
+
92
+
93
+ def _adult_supervision(safety: dict, age_group: str) -> bool:
94
+ if isinstance(safety, dict) and "adult_supervision_required" in safety:
95
+ return bool(safety["adult_supervision_required"])
96
+ return age_group in ("children_only", "teens", "mixed_family")
97
+
98
+
99
+ def _forbidden_behaviors(safety: dict, extra_out_of_bounds: list[str]) -> list[str]:
100
+ items: list[str] = []
101
+ if isinstance(safety, dict):
102
+ items += list(safety.get("exclusion_zones", []) or [])
103
+ items += list(safety.get("physical_limits", []) or [])
104
+ items += list(extra_out_of_bounds or [])
105
+ # de-dup, keep order, cap to a reasonable size
106
+ seen, out = set(), []
107
+ for it in items:
108
+ s = str(it).strip()
109
+ if s and s.lower() not in seen:
110
+ seen.add(s.lower())
111
+ out.append(s)
112
+ return out[:12] or ["Entering private property", "Crossing busy roads", "Approaching strangers"]
113
+
114
+
115
+ _STOP_CONDITIONS = [
116
+ "If a player feels unsafe, the game stops immediately.",
117
+ "If weather becomes severe, players relocate to shelter.",
118
+ "If anyone is injured, organizers call emergency services.",
119
+ ]
120
+
121
+
122
+ # ── per-type task builders ────────────────────────────────────────────────────
123
+
124
+ def _tasks_from_scavenger(output: dict) -> list[dict]:
125
+ tasks = []
126
+ for t in output.get("tasks", []):
127
+ hints = t.get("hints", {}) or {}
128
+ if isinstance(hints, dict):
129
+ hint = hints.get("hint_1") or hints.get("hint_2") or hints.get("hint_3") or "Look carefully around the area."
130
+ location_hint = hints.get("hint_3") or hints.get("hint_2") or t.get("description", "")
131
+ else:
132
+ hint = (hints[0] if isinstance(hints, list) and hints else "Look carefully around the area.")
133
+ location_hint = t.get("description", "")
134
+ safety_flags = t.get("safety_flags", []) or []
135
+ tasks.append({
136
+ "task_id": t.get("task_id", f"T{len(tasks)+1:02d}"),
137
+ "title": t.get("title", _short_title(t.get("description", ""))),
138
+ "description": t.get("description", ""),
139
+ "location_hint": _first_sentence(location_hint, 200) or "Explore the designated area.",
140
+ "points": int(t.get("points", 10) or 10),
141
+ "time_limit_minutes": t.get("estimated_time_minutes"),
142
+ "proof_type": _proof_type_for_task(t),
143
+ "hint": _first_sentence(hint, 200),
144
+ "safety_note": "; ".join(safety_flags) if safety_flags else "Stay on public paths and stay aware of surroundings.",
145
+ })
146
+ return tasks
147
+
148
+
149
+ def _tasks_from_hide_and_seek(output: dict) -> list[dict]:
150
+ rules = output.get("rules", {}) or {}
151
+ tlimit = rules.get("round_time_minutes")
152
+ tasks = []
153
+ for z in output.get("hiding_zones", []):
154
+ desc = z.get("description", "")
155
+ tasks.append({
156
+ "task_id": z.get("zone_id", f"H{len(tasks)+1:02d}"),
157
+ "title": f"Hiding zone {z.get('zone_id', '')}: {_short_title(desc)}".strip(),
158
+ "description": desc,
159
+ "location_hint": _first_sentence(desc, 200) or "Find concealment within the play area.",
160
+ "points": _concealment_points(z.get("concealment_rating", "medium")),
161
+ "time_limit_minutes": tlimit,
162
+ "proof_type": "observation",
163
+ "hint": _first_sentence(z.get("risk_note", ""), 200) or "Watch sightlines and keep an escape route.",
164
+ "safety_note": "; ".join(z.get("safety_flags", []) or []) or _first_sentence(z.get("risk_note", ""), 160) or "Stay aware of footing and surroundings.",
165
+ })
166
+ return tasks
167
+
168
+
169
+ def _tasks_from_tag(output: dict) -> list[dict]:
170
+ rules = output.get("rules", {}) or {}
171
+ tlimit = rules.get("round_time_minutes")
172
+ tasks = []
173
+ for z in output.get("safe_zones", []):
174
+ desc = z.get("description", "")
175
+ tasks.append({
176
+ "task_id": z.get("zone_id", f"S{len(tasks)+1:02d}"),
177
+ "title": f"Safe zone {z.get('zone_id', '')}: {_short_title(desc)}".strip(),
178
+ "description": desc,
179
+ "location_hint": _first_sentence(desc, 200) or "Locate the safe zone within the arena.",
180
+ "points": 15,
181
+ "time_limit_minutes": tlimit,
182
+ "proof_type": "observation",
183
+ "hint": z.get("capacity_rule", "Reach the safe zone before being tagged."),
184
+ "safety_note": "; ".join(z.get("safety_flags", []) or []) or "Watch footing and avoid collisions.",
185
+ })
186
+ # enrich with a couple of movement-feature objectives if few safe zones
187
+ mf = output.get("movement_features", {}) or {}
188
+ for i, oz in enumerate(mf.get("open_zones", [])[: max(0, 3 - len(tasks))]):
189
+ tasks.append({
190
+ "task_id": f"M{i+1:02d}",
191
+ "title": f"Open ground: {_short_title(oz)}",
192
+ "description": f"Use the open zone tactically: {oz}",
193
+ "location_hint": _first_sentence(oz, 200),
194
+ "points": 10,
195
+ "time_limit_minutes": tlimit,
196
+ "proof_type": "observation",
197
+ "hint": "Open zones are exposed — keep moving and watch for taggers.",
198
+ "safety_note": "Avoid collisions and watch for other players.",
199
+ })
200
+ return tasks
201
+
202
+
203
+ # ── public API ────────────────────────────────────────────────────────────────
204
+
205
+ def convert_record_to_game_schema(record: dict) -> Optional[dict]:
206
+ """Convert one raw dataset record into a game_schema.json-shaped game dict.
207
+
208
+ Args:
209
+ record: raw dataset record with ``id``, ``input`` and ``output``.
210
+
211
+ Returns:
212
+ A dict matching ``app/schemas/game_schema.json`` (caller validates), or
213
+ ``None`` if the record is missing required pieces.
214
+ """
215
+ inp = record.get("input", {}) or {}
216
+ out = record.get("output", {}) or {}
217
+ if not inp or not out:
218
+ return None
219
+
220
+ loc = inp.get("location", {}) or {}
221
+ players = inp.get("players", {}) or {}
222
+ prefs = inp.get("preferences", {}) or {}
223
+ safety = out.get("safety_constraints", {}) or {}
224
+ game_type = inp.get("game_type", "scavenger_hunt")
225
+ theme = prefs.get("theme", "general")
226
+ age_group = players.get("age_group", "adults")
227
+
228
+ if game_type == "hide_and_seek":
229
+ tasks = _tasks_from_hide_and_seek(out)
230
+ play_area = out.get("play_area", {}) or {}
231
+ meeting_point = play_area.get("safe_base_description") or f"Safe base in {loc.get('city', 'the area')}"
232
+ allowed_zone = play_area.get("boundary_description") or loc.get("area_type", "")
233
+ out_of_bounds = play_area.get("out_of_bounds", []) or []
234
+ elif game_type == "tag":
235
+ tasks = _tasks_from_tag(out)
236
+ arena = out.get("arena", {}) or {}
237
+ szs = out.get("safe_zones", []) or []
238
+ meeting_point = (szs[0].get("description") if szs else None) or f"Arena entry in {loc.get('city', 'the area')}"
239
+ allowed_zone = arena.get("boundary_description") or loc.get("area_type", "")
240
+ out_of_bounds = arena.get("out_of_bounds", []) or []
241
+ else: # scavenger_hunt (and any fallback)
242
+ tasks = _tasks_from_scavenger(out)
243
+ meeting_point = f"Central meeting point in {loc.get('area_type') or loc.get('city', 'the area')}"
244
+ allowed_zone = loc.get("area_type") or f"Public areas of {loc.get('city', 'the city')}"
245
+ out_of_bounds = []
246
+
247
+ if not tasks:
248
+ return None
249
+
250
+ # score_rules: derive from rules/scoring metadata, deterministic strings
251
+ rules_obj = out.get("rules", {}) or {}
252
+ score_rules = ["Each completed task awards its listed points."]
253
+ if rules_obj.get("scoring_method"):
254
+ score_rules.append(f"Scoring method: {rules_obj['scoring_method']}.")
255
+ score_rules.append("Failed or skipped tasks award no points.")
256
+ if out.get("scoring_summary") or out.get("scoring"):
257
+ score_rules.append("Bonus and penalty points follow the standard scoring summary.")
258
+
259
+ motifs = (loc.get("landscape_tags", []) or [])[:3] or ["exploration", "teamwork"]
260
+
261
+ game = {
262
+ "game_id": record.get("id", "game-unknown"),
263
+ "game_type": game_type,
264
+ "title": out.get("game_title", "City Game"),
265
+ "theme": theme,
266
+ "setup": {
267
+ "city": loc.get("city", "Unknown"),
268
+ "area": loc.get("area_type") or loc.get("city", "downtown"),
269
+ "meeting_point": _first_sentence(meeting_point, 200),
270
+ "duration_minutes": int(prefs.get("duration_minutes", 45) or 45),
271
+ "num_players": int(players.get("count", 4) or 4),
272
+ },
273
+ "rules": _flatten_rules(rules_obj) or ["Complete tasks within the time limit.", "Stay within the play area."],
274
+ "tasks": tasks,
275
+ "global_hints": [
276
+ "Plan a route before you start and manage your time.",
277
+ "Work as a team and stay within the allowed area.",
278
+ "Read each task carefully before acting.",
279
+ ],
280
+ "score_rules": score_rules,
281
+ "tie_breaker": "If scores are tied, the team with the earliest completion time wins.",
282
+ "safety": {
283
+ "allowed_zone": _first_sentence(allowed_zone, 250) or "Designated public area",
284
+ "forbidden_behaviors": _forbidden_behaviors(safety, out_of_bounds),
285
+ "adult_supervision": _adult_supervision(safety, age_group),
286
+ "stop_conditions": list(_STOP_CONDITIONS),
287
+ },
288
+ "story_seed": {
289
+ "tone": _tone_for(game_type, theme),
290
+ "motifs": motifs,
291
+ "recap_style": "episode_recap",
292
+ },
293
+ }
294
+ return game
training/eval_gguf.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate a GGUF model on the held-out CityQuest val set via llama.cpp.
2
+
3
+ Feeds each val sample's (system, user) prompt to the model exactly as the app does
4
+ (create_chat_completion with the serve-time decoding params), extracts the JSON and
5
+ validates it against game_schema.json. Reports JSON-parse rate and schema-pass rate.
6
+
7
+ Run it once for the fine-tuned model and once for the stock base to compare; the
8
+ plan gates the model swap on fine-tuned >= baseline.
9
+
10
+ Usage:
11
+ # fine-tuned model
12
+ python training/eval_gguf.py --repo NANI-Nithin/CityQuest-Nemotron-3-Nano-4B-GGUF \\
13
+ --file CityQuest-Nemotron-3-Nano-4B-Q4_K_M.gguf
14
+
15
+ # baseline (stock) model
16
+ python training/eval_gguf.py --repo nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF \\
17
+ --file NVIDIA-Nemotron3-Nano-4B-Q4_K_M.gguf
18
+
19
+ --limit N evaluate only the first N val samples (quick smoke test)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ REPO_ROOT = Path(__file__).resolve().parent.parent
30
+ sys.path.insert(0, str(REPO_ROOT))
31
+
32
+ from app.services.generator import extract_json # noqa: E402
33
+ from app.services.schema_validator import validate_game_schema # noqa: E402
34
+
35
+ VAL_PATH = Path(__file__).resolve().parent / "data" / "val.jsonl"
36
+
37
+
38
+ def main() -> None:
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--repo", required=True, help="HF repo id of the GGUF model")
41
+ ap.add_argument("--file", required=True, help="GGUF filename within the repo")
42
+ ap.add_argument("--limit", type=int, default=0, help="evaluate only first N samples")
43
+ args = ap.parse_args()
44
+
45
+ from llama_cpp import Llama
46
+
47
+ n_gpu_layers = 0
48
+ try:
49
+ import torch
50
+ if torch.cuda.is_available():
51
+ n_gpu_layers = -1
52
+ except ImportError:
53
+ pass
54
+
55
+ print(f"[eval] loading {args.repo}/{args.file} (gpu_layers={n_gpu_layers})")
56
+ llm = Llama.from_pretrained(
57
+ repo_id=args.repo, filename=args.file,
58
+ n_ctx=8192, n_gpu_layers=n_gpu_layers, verbose=False,
59
+ )
60
+
61
+ rows = [json.loads(l) for l in VAL_PATH.read_text(encoding="utf-8").splitlines() if l.strip()]
62
+ if args.limit:
63
+ rows = rows[: args.limit]
64
+
65
+ parsed_ok = schema_ok = 0
66
+ failures: list[str] = []
67
+ for i, row in enumerate(rows, 1):
68
+ # use only system + user (drop the gold assistant turn)
69
+ messages = [m for m in row["messages"] if m["role"] in ("system", "user")]
70
+ result = llm.create_chat_completion(
71
+ messages=messages, max_tokens=8192, temperature=0.3, top_p=0.9, stop=["```"],
72
+ )
73
+ text = result["choices"][0]["message"]["content"].strip()
74
+ js = extract_json(text)
75
+ game = None
76
+ if js:
77
+ try:
78
+ game = json.loads(js)
79
+ parsed_ok += 1
80
+ except json.JSONDecodeError:
81
+ pass
82
+ if game is not None:
83
+ ok, errs = validate_game_schema(game)
84
+ if ok:
85
+ schema_ok += 1
86
+ elif len(failures) < 10:
87
+ failures.append(f"sample {i}: {errs[:1]}")
88
+ print(f" [{i}/{len(rows)}] parsed={'Y' if game else 'N'} "
89
+ f"schema={'Y' if game and validate_game_schema(game)[0] else 'N'}", end="\r")
90
+
91
+ n = len(rows)
92
+ print("\n" + "=" * 50)
93
+ print(f"Model: {args.repo}/{args.file}")
94
+ print(f" JSON parse rate : {parsed_ok}/{n} ({100*parsed_ok/n:.1f}%)")
95
+ print(f" Schema pass rate: {schema_ok}/{n} ({100*schema_ok/n:.1f}%)")
96
+ if failures:
97
+ print(" Sample schema failures:")
98
+ for f in failures:
99
+ print(f" - {f}")
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
training/prepare_dataset.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build chat-format SFT data for fine-tuning Nemotron on CityQuest game generation.
2
+
3
+ For every record in ``app/data/<game>/dataset.json`` this produces one chat sample
4
+ that mirrors *exactly* what the model sees at serve time:
5
+
6
+ system = "You output only valid JSON. No other text." (see generator.py)
7
+ user = build_generation_prompt(config, retrieved) (serve prompt builder)
8
+ assistant = <game_schema.json-shaped JSON> (converted target)
9
+
10
+ Key correctness details:
11
+ * The user prompt is built with the real ``build_generation_prompt`` so train and
12
+ serve prompts are identical (same template, retrieved-examples formatting,
13
+ city context and embedded output schema).
14
+ * Retrieval is **leave-one-out**: the target record is removed from the pool so its
15
+ own content never appears in the prompt's "Retrieved Examples".
16
+ * Targets are converted to ``game_schema.json`` shape (see convert_to_game_schema)
17
+ and validated; the app only consumes that shape.
18
+
19
+ Outputs ``training/data/train.jsonl`` and ``training/data/val.jsonl`` in the
20
+ ``{"messages": [...]}`` chat format consumed by train_modal.py.
21
+
22
+ Usage:
23
+ python training/prepare_dataset.py # fetch + cache city context
24
+ python training/prepare_dataset.py --no-city-context # faster, offline
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import random
32
+ import sys
33
+ from collections import Counter
34
+ from pathlib import Path
35
+
36
+ REPO_ROOT = Path(__file__).resolve().parent.parent
37
+ sys.path.insert(0, str(REPO_ROOT))
38
+
39
+ from app.services import city_context # noqa: E402
40
+ from app.services.generator import build_generation_prompt # noqa: E402
41
+ from app.services.retrieval import ( # noqa: E402
42
+ load_games_dataset,
43
+ normalize_game_record,
44
+ retrieve_examples,
45
+ )
46
+ from app.services.schema_validator import validate_game_schema # noqa: E402
47
+
48
+ from convert_to_game_schema import convert_record_to_game_schema # noqa: E402
49
+
50
+ SYSTEM_PROMPT = "You output only valid JSON. No other text."
51
+ DATA_DIR = REPO_ROOT / "app" / "data"
52
+ GAME_TYPES = ["scavenger_hunt", "hide_and_seek", "tag"]
53
+ OUT_DIR = Path(__file__).resolve().parent / "data"
54
+ CITY_CACHE_PATH = Path(__file__).resolve().parent / "city_context_cache.json"
55
+ VAL_FRACTION = 0.10
56
+ SEED = 13
57
+
58
+
59
+ def _config_from_record(record: dict) -> dict:
60
+ """Flatten a raw dataset record's nested input into the flat config dict
61
+ that ``build_generation_prompt`` and ``retrieve_examples`` expect."""
62
+ inp = record.get("input", {}) or {}
63
+ loc = inp.get("location", {}) or {}
64
+ players = inp.get("players", {}) or {}
65
+ prefs = inp.get("preferences", {}) or {}
66
+ return {
67
+ "game_type": inp.get("game_type", "scavenger_hunt"),
68
+ "city": loc.get("city", ""),
69
+ "area": loc.get("area_type") or loc.get("city", ""),
70
+ "location_type": loc.get("area_type", ""),
71
+ "duration_minutes": prefs.get("duration_minutes"),
72
+ "num_players": players.get("count"),
73
+ "difficulty": prefs.get("difficulty", ""),
74
+ "age_group": players.get("age_group", ""),
75
+ "landscape_tags": loc.get("landscape_tags", []),
76
+ "theme": prefs.get("theme", ""),
77
+ "mobility": players.get("mobility", "standard"),
78
+ "allow_transport": prefs.get("allow_transport", False),
79
+ }
80
+
81
+
82
+ def _load_city_cache() -> None:
83
+ if CITY_CACHE_PATH.exists():
84
+ try:
85
+ cached = json.loads(CITY_CACHE_PATH.read_text(encoding="utf-8"))
86
+ city_context._cache.update(cached)
87
+ print(f"[prep] Loaded {len(cached)} cached city contexts")
88
+ except Exception as e: # noqa: BLE001
89
+ print(f"[prep] Could not load city cache: {e}")
90
+
91
+
92
+ def _save_city_cache() -> None:
93
+ try:
94
+ CITY_CACHE_PATH.write_text(
95
+ json.dumps(city_context._cache, ensure_ascii=False, indent=1),
96
+ encoding="utf-8",
97
+ )
98
+ print(f"[prep] Saved {len(city_context._cache)} city contexts → {CITY_CACHE_PATH.name}")
99
+ except Exception as e: # noqa: BLE001
100
+ print(f"[prep] Could not save city cache: {e}")
101
+
102
+
103
+ def build_samples(no_city_context: bool) -> list[dict]:
104
+ # Load every record and keep (raw, normalized) pairs for retrieval.
105
+ raw_by_type: dict[str, list[dict]] = {}
106
+ norm_all: list[dict] = []
107
+ for gt in GAME_TYPES:
108
+ path = DATA_DIR / gt / "dataset.json"
109
+ raw = load_games_dataset(str(path))
110
+ raw_by_type[gt] = raw
111
+ norm_all.extend(normalize_game_record(r) for r in raw)
112
+ print(f"[prep] {gt}: {len(raw)} records")
113
+
114
+ if no_city_context:
115
+ # Stub out the network fetch: every city resolves to an empty context,
116
+ # exactly matching serve-time degradation when Wikipedia is unavailable.
117
+ city_context.get_city_context = lambda c: { # type: ignore[assignment]
118
+ "landmarks": [], "districts": [], "parks": [], "description": ""
119
+ }
120
+
121
+ samples: list[dict] = []
122
+ skipped = 0
123
+ for gt in GAME_TYPES:
124
+ for record in raw_by_type[gt]:
125
+ rid = record.get("id")
126
+ target = convert_record_to_game_schema(record)
127
+ if target is None:
128
+ skipped += 1
129
+ continue
130
+ ok, errors = validate_game_schema(target)
131
+ if not ok:
132
+ skipped += 1
133
+ print(f"[prep] SKIP {rid}: target failed schema: {errors[:2]}")
134
+ continue
135
+
136
+ config = _config_from_record(record)
137
+ # Leave-one-out retrieval pool (exclude this exact record by id).
138
+ pool = [r for r in norm_all if r.get("id") != rid]
139
+ retrieved = retrieve_examples(config, pool, k=3)
140
+ user_prompt = build_generation_prompt(config, retrieved)
141
+
142
+ samples.append({
143
+ "id": rid,
144
+ "game_type": gt,
145
+ "messages": [
146
+ {"role": "system", "content": SYSTEM_PROMPT},
147
+ {"role": "user", "content": user_prompt},
148
+ {"role": "assistant", "content": json.dumps(target, ensure_ascii=False)},
149
+ ],
150
+ })
151
+
152
+ print(f"[prep] Built {len(samples)} samples, skipped {skipped}")
153
+ return samples
154
+
155
+
156
+ def split_and_write(samples: list[dict]) -> None:
157
+ rng = random.Random(SEED)
158
+ # Stratified split by game_type.
159
+ by_type: dict[str, list[dict]] = {gt: [] for gt in GAME_TYPES}
160
+ for s in samples:
161
+ by_type[s["game_type"]].append(s)
162
+
163
+ train, val = [], []
164
+ for gt, items in by_type.items():
165
+ rng.shuffle(items)
166
+ n_val = max(1, int(len(items) * VAL_FRACTION))
167
+ val.extend(items[:n_val])
168
+ train.extend(items[n_val:])
169
+ rng.shuffle(train)
170
+ rng.shuffle(val)
171
+
172
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
173
+ for name, rows in (("train", train), ("val", val)):
174
+ path = OUT_DIR / f"{name}.jsonl"
175
+ with path.open("w", encoding="utf-8") as f:
176
+ for r in rows:
177
+ f.write(json.dumps({"messages": r["messages"]}, ensure_ascii=False) + "\n")
178
+ print(f"[prep] Wrote {len(rows)} → {path}")
179
+
180
+ # Token/length statistics (approx: ~4 chars/token) for sizing max_seq_length.
181
+ lengths = []
182
+ for s in samples:
183
+ chars = sum(len(m["content"]) for m in s["messages"])
184
+ lengths.append(chars)
185
+ lengths.sort()
186
+ approx_tok = [c / 4 for c in lengths]
187
+ n = len(lengths)
188
+ def pct(p): # noqa: ANN001
189
+ return approx_tok[min(n - 1, int(n * p))]
190
+ print("\n[prep] Length stats (approx tokens, ~4 chars/token):")
191
+ print(f" count={n} median={pct(0.5):.0f} p90={pct(0.9):.0f} "
192
+ f"p99={pct(0.99):.0f} max={approx_tok[-1]:.0f}")
193
+ print(f" per-type counts: {dict(Counter(s['game_type'] for s in samples))}")
194
+ if approx_tok[-1] > 8192:
195
+ print(" ⚠ longest sample exceeds 8192 approx tokens — consider raising max_seq_length")
196
+
197
+
198
+ def main() -> None:
199
+ ap = argparse.ArgumentParser()
200
+ ap.add_argument("--no-city-context", action="store_true",
201
+ help="Skip Wikipedia fetch; build prompts with empty city context.")
202
+ args = ap.parse_args()
203
+
204
+ if not args.no_city_context:
205
+ _load_city_cache()
206
+ samples = build_samples(args.no_city_context)
207
+ if not args.no_city_context:
208
+ _save_city_cache()
209
+ split_and_write(samples)
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
training/requirements-train.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training-only dependencies for the Modal GPU image (train_modal.py).
2
+ # NOT installed into the app's serve requirements.txt.
3
+ #
4
+ # We load Nemotron 3 Nano 4B (arch: nemotron_h) directly with transformers'
5
+ # native implementation + PEFT LoRA — no Unsloth (it doesn't recognise this
6
+ # brand-new hybrid Mamba arch). torch and the Mamba CUDA kernels (mamba-ssm,
7
+ # causal-conv1d — required, the naive fallback OOMs) are installed in the Modal
8
+ # image (train_modal.py), which uses a CUDA-devel base for nvcc.
9
+ transformers>=5.4.0
10
+ peft>=0.13.0
11
+ accelerate>=1.0.0
12
+ datasets>=3.0.0
13
+ huggingface_hub>=0.26.0
14
+ einops
15
+ sentencepiece
16
+ protobuf
training/train_modal.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fine-tune NVIDIA Nemotron 3 Nano 4B on CityQuest data (LoRA) on Modal, then
2
+ merge, convert to GGUF Q4_K_M and upload to Hugging Face.
3
+
4
+ The model (`nemotron_h`, a hybrid Mamba-Transformer) is loaded **directly from
5
+ Hugging Face with plain `transformers` + PEFT** — no Unsloth (its model-type
6
+ detector doesn't recognise this brand-new architecture). transformers 5.x ships a
7
+ native NemotronH implementation with a pure-PyTorch fallback, so the CUDA Mamba
8
+ kernels (mamba-ssm) are optional; training just runs a bit slower without them.
9
+
10
+ Pipeline (one A100-80GB):
11
+ 1. Load base (bf16) from HF, attach LoRA to all linear layers (router/lm_head excluded).
12
+ 2. SFT on training/data/train.jsonl with response-only loss masking; eval on val.jsonl.
13
+ 3. Merge LoRA → 16-bit safetensors (+ tokenizer & chat template).
14
+ 4. Convert merged model → GGUF Q4_K_M via llama.cpp.
15
+ 5. Upload the .gguf to HF_REPO so generator.py can pull it.
16
+
17
+ Run (after `modal token new` + the HF secret — see training/README.md):
18
+ modal run training/train_modal.py::main
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ from pathlib import Path
25
+
26
+ import modal
27
+
28
+ # ── Configuration ─────────────────────────────────────────────────────────────
29
+ BASE_MODEL = "nvidia/NVIDIA-Nemotron-3-Nano-4B-BF16" # official full-precision base on HF
30
+ HF_REPO = "NANI-Nithin/CityQuest-Nemotron-3-Nano-4B-GGUF"
31
+ GGUF_OUTFILE = "CityQuest-Nemotron-3-Nano-4B-Q4_K_M.gguf"
32
+ # llama.cpp commit whose convert_hf_to_gguf handles the DENSE nemotron_h 4B
33
+ # (earlier master misclassified it as MoE → KeyError 'moe_intermediate_size').
34
+ LLAMA_CPP_COMMIT = "e36a602ba38a26206c749ba4fb5dcf481bfd92db"
35
+
36
+ # Stock baseline GGUF (matches generator.py's current constants) for comparison.
37
+ BASELINE_REPO = "nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF"
38
+ BASELINE_FILE = "NVIDIA-Nemotron3-Nano-4B-Q4_K_M.gguf"
39
+
40
+ MAX_SEQ_LEN = 8192 # matches serve-time n_ctx; covers our longest sample (~5.4k)
41
+ NUM_EPOCHS = 3
42
+ LEARNING_RATE = 2e-4
43
+ LORA_R = 16
44
+ LORA_ALPHA = 16
45
+ BATCH_SIZE = 1
46
+ GRAD_ACCUM = 16 # effective batch 16
47
+ ASSISTANT_HEADER = "<|im_start|>assistant\n" # from the model's chat template
48
+
49
+ LOCAL_DATA = Path(__file__).resolve().parent / "data"
50
+ REMOTE_DATA = "/root/data"
51
+ LOCAL_SCHEMA = Path(__file__).resolve().parent.parent / "app" / "schemas" / "game_schema.json"
52
+ REMOTE_SCHEMA = "/root/game_schema.json"
53
+
54
+ # ── Training image ─────────────────────────────────────────────────────────
55
+ # CUDA-devel base (provides nvcc) so we can build the Mamba CUDA kernels. Without
56
+ # mamba-ssm/causal-conv1d the native nemotron_h falls back to a naive O(L^2) Mamba
57
+ # path that OOMs at our sequence lengths — the fused kernels are required here.
58
+ image = (
59
+ modal.Image.from_registry("nvidia/cuda:12.4.1-devel-ubuntu22.04", add_python="3.11")
60
+ .apt_install("git", "build-essential", "cmake", "curl", "libcurl4-openssl-dev")
61
+ .env({
62
+ "TORCH_CUDA_ARCH_LIST": "8.0", "MAX_JOBS": "4", "CC": "gcc", "CXX": "g++",
63
+ "CAUSAL_CONV1D_FORCE_BUILD": "TRUE", "MAMBA_FORCE_BUILD": "TRUE",
64
+ })
65
+ # Single controlled install pass. A constraints file pins torch==2.6.0 so NOTHING
66
+ # (transformers/peft/accelerate) can swap it for the PyPI cu130 build mid-install —
67
+ # that version drift is what broke the kernel ABI (undefined c10::cuda symbol).
68
+ # The Mamba kernels are force-compiled FROM SOURCE against this exact torch, then
69
+ # imported AT BUILD TIME so any ABI mismatch fails the build (CPU builder, ~1 min,
70
+ # no GPU burned) with the torch version printed.
71
+ .run_commands(
72
+ "pip install --upgrade pip",
73
+ "pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124",
74
+ "printf 'torch==2.6.0\\n' > /root/constraints.txt",
75
+ "pip install -c /root/constraints.txt ninja packaging wheel setuptools "
76
+ "'transformers>=5.4.0' 'peft>=0.13.0' 'accelerate>=1.0.0' 'datasets>=3.0.0' "
77
+ "huggingface_hub einops sentencepiece protobuf gguf 'numpy<2.0'",
78
+ "python -c \"import torch; print('[build] torch', torch.__version__, torch.version.cuda)\"",
79
+ "pip install -c /root/constraints.txt --no-build-isolation causal-conv1d",
80
+ # Pin 2.3.1: newer 2.3.2.post1 drags in tilelang/triton>=3.5 which conflict
81
+ # with torch 2.6's triton 3.2 (pip would backtrack to 2.3.1 anyway).
82
+ "pip install -c /root/constraints.txt --no-build-isolation mamba-ssm==2.3.1",
83
+ # transformers' lazy_load_kernel prefers the HF `kernels` hub package (no working
84
+ # mamba build → silent fallback to the OOM naive path). Remove it so transformers
85
+ # imports the mamba_ssm/causal_conv1d we just compiled.
86
+ "pip uninstall -y kernels || true",
87
+ # Build-time ABI gate: import the compiled CUDA C-extension only (this is what
88
+ # had the undefined-symbol error). It validates the torch ABI without triggering
89
+ # Triton autotune, which needs a GPU the CPU image-builder doesn't have.
90
+ "python -c \"import torch, selective_scan_cuda; "
91
+ "print('[build] CUDA ext ABI OK on torch', torch.__version__)\"",
92
+ )
93
+ .add_local_dir(str(LOCAL_DATA), remote_path=REMOTE_DATA)
94
+ )
95
+
96
+ # Eval image: CUDA *runtime* base so the cu124 llama-cpp-python wheel finds
97
+ # libcudart.so.12 (debian_slim lacks the CUDA runtime libs).
98
+ eval_image = (
99
+ modal.Image.from_registry("nvidia/cuda:12.4.1-runtime-ubuntu22.04", add_python="3.11")
100
+ .pip_install("huggingface_hub", "hf_transfer", "jsonschema")
101
+ .pip_install(
102
+ "llama-cpp-python",
103
+ extra_index_url="https://abetlen.github.io/llama-cpp-python/whl/cu124",
104
+ )
105
+ .env({"HF_HUB_ENABLE_HF_TRANSFER": "1"})
106
+ .add_local_dir(str(LOCAL_DATA), remote_path=REMOTE_DATA)
107
+ .add_local_file(str(LOCAL_SCHEMA), remote_path=REMOTE_SCHEMA)
108
+ )
109
+
110
+ app = modal.App("cityquest-nemotron-finetune", image=image)
111
+
112
+ hf_cache = modal.Volume.from_name("cityquest-hf-cache", create_if_missing=True)
113
+ outputs_vol = modal.Volume.from_name("cityquest-outputs", create_if_missing=True)
114
+
115
+
116
+ def _find_subsequence(seq: list[int], sub: list[int]) -> int:
117
+ """Return the start index of the last occurrence of ``sub`` in ``seq``, else -1."""
118
+ if not sub:
119
+ return -1
120
+ for start in range(len(seq) - len(sub), -1, -1):
121
+ if seq[start:start + len(sub)] == sub:
122
+ return start
123
+ return -1
124
+
125
+
126
+ @app.function(
127
+ gpu="A100-80GB",
128
+ timeout=3 * 60 * 60,
129
+ secrets=[modal.Secret.from_name("huggingface")],
130
+ volumes={"/root/.cache/huggingface": hf_cache, "/root/outputs": outputs_vol},
131
+ )
132
+ def train():
133
+ import json
134
+ import os
135
+
136
+ import torch
137
+ import torch.nn as nn
138
+ from datasets import load_dataset
139
+ from peft import LoraConfig, get_peft_model
140
+ from transformers import (
141
+ AutoModelForCausalLM,
142
+ AutoTokenizer,
143
+ DataCollatorForSeq2Seq,
144
+ Trainer,
145
+ TrainerCallback,
146
+ TrainingArguments,
147
+ )
148
+ from transformers.trainer_utils import get_last_checkpoint
149
+
150
+ merged_dir = "/root/outputs/merged_16bit"
151
+ gguf_dir = "/root/outputs/gguf"
152
+
153
+ # ── 0. Mamba-kernel diagnostic + hard gate ─────────────────────────────
154
+ # The native nemotron_h falls back to a naive O(L^2) Mamba path (OOMs at our
155
+ # sequence lengths) unless mamba-ssm/causal-conv1d import cleanly. Surface the
156
+ # real reason and fail fast (seconds) instead of OOMing after model load.
157
+ print(f"[diag] torch={torch.__version__} cuda_avail={torch.cuda.is_available()} "
158
+ f"torch.cuda={torch.version.cuda}")
159
+ try:
160
+ import kernels # noqa: F401
161
+ print("[diag] WARNING: `kernels` package still installed (may hijack kernel loading)")
162
+ except ImportError:
163
+ print("[diag] `kernels` package absent (good — will import compiled mamba_ssm)")
164
+ from transformers.utils.import_utils import (
165
+ is_causal_conv1d_available, is_mamba_2_ssm_available,
166
+ )
167
+ print(f"[diag] is_mamba_2_ssm_available={is_mamba_2_ssm_available()} "
168
+ f"is_causal_conv1d_available={is_causal_conv1d_available()}")
169
+ _kernel_err = None
170
+ try:
171
+ import mamba_ssm
172
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined # noqa: F401
173
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update # noqa: F401
174
+ import causal_conv1d # noqa: F401
175
+ from causal_conv1d import causal_conv1d_fn # noqa: F401
176
+ print(f"[diag] mamba_ssm {getattr(mamba_ssm, '__version__', '?')} + causal_conv1d import OK")
177
+ except Exception as e: # noqa: BLE001
178
+ import traceback
179
+ _kernel_err = traceback.format_exc()
180
+ print(f"[diag] KERNEL IMPORT FAILED:\n{_kernel_err}")
181
+ if _kernel_err is not None:
182
+ raise RuntimeError(
183
+ "Mamba CUDA kernels not importable — training would fall back to the "
184
+ "OOM-prone naive path. See [diag] traceback above for the root cause."
185
+ )
186
+
187
+ # ── 1. Load base + LoRA (native transformers, no Unsloth) ──────────────
188
+ # IMPORTANT: trust_remote_code=False → use transformers' *native* nemotron_h
189
+ # implementation, which falls back to a pure-PyTorch path when the mamba-ssm /
190
+ # causal-conv1d CUDA kernels are absent (it only warns). NVIDIA's *remote* code
191
+ # hard-raises ImportError without those kernels.
192
+ print(f"[train] loading base from HF: {BASE_MODEL}")
193
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
194
+ if tokenizer.pad_token is None:
195
+ tokenizer.pad_token = tokenizer.eos_token # this model ships no pad token
196
+ model = AutoModelForCausalLM.from_pretrained(
197
+ BASE_MODEL,
198
+ dtype=torch.bfloat16,
199
+ low_cpu_mem_usage=True,
200
+ attn_implementation="sdpa", # memory-efficient attention for the transformer layers
201
+ )
202
+ model.config.pad_token_id = tokenizer.pad_token_id
203
+ model.config.use_cache = False
204
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
205
+ model.enable_input_require_grads()
206
+
207
+ # Discover LoRA targets: every nn.Linear leaf name except the LM head and any
208
+ # MoE router (router weights shouldn't be adapted). Covers attention + MLP +
209
+ # Mamba projections regardless of the exact arch naming.
210
+ target_modules = set()
211
+ for name, module in model.named_modules():
212
+ if isinstance(module, nn.Linear):
213
+ leaf = name.split(".")[-1]
214
+ if leaf in ("lm_head",) or "router" in name.lower():
215
+ continue
216
+ target_modules.add(leaf)
217
+ target_modules = sorted(target_modules)
218
+ print(f"[train] LoRA target modules: {target_modules}")
219
+
220
+ model = get_peft_model(model, LoraConfig(
221
+ r=LORA_R, lora_alpha=LORA_ALPHA, lora_dropout=0.0, bias="none",
222
+ task_type="CAUSAL_LM", target_modules=target_modules,
223
+ ))
224
+ model.print_trainable_parameters()
225
+
226
+ # ── 2. Tokenize with response-only label masking ───────────────────────
227
+ header_ids = tokenizer(ASSISTANT_HEADER, add_special_tokens=False)["input_ids"]
228
+
229
+ def tokenize_and_mask(row):
230
+ # enable_thinking=False keeps non-reasoning/JSON-only mode (matches the
231
+ # serve-time "output only valid JSON" system prompt).
232
+ try:
233
+ text = tokenizer.apply_chat_template(
234
+ row["messages"], tokenize=False, add_generation_prompt=False,
235
+ enable_thinking=False,
236
+ )
237
+ except TypeError:
238
+ text = tokenizer.apply_chat_template(
239
+ row["messages"], tokenize=False, add_generation_prompt=False,
240
+ )
241
+ enc = tokenizer(text, truncation=True, max_length=MAX_SEQ_LEN, add_special_tokens=False)
242
+ input_ids = enc["input_ids"]
243
+ labels = list(input_ids)
244
+ cut = _find_subsequence(input_ids, header_ids)
245
+ if cut != -1:
246
+ for i in range(cut + len(header_ids)):
247
+ labels[i] = -100 # mask system + user; train only on the JSON answer
248
+ enc["labels"] = labels
249
+ return enc
250
+
251
+ train_ds = load_dataset("json", data_files=f"{REMOTE_DATA}/train.jsonl", split="train")
252
+ val_ds = load_dataset("json", data_files=f"{REMOTE_DATA}/val.jsonl", split="train")
253
+ train_ds = train_ds.map(tokenize_and_mask, remove_columns=train_ds.column_names)
254
+ val_ds = val_ds.map(tokenize_and_mask, remove_columns=val_ds.column_names)
255
+ print(f"[train] train={len(train_ds)} val={len(val_ds)}")
256
+
257
+ collator = DataCollatorForSeq2Seq(tokenizer, label_pad_token_id=-100, padding="longest")
258
+
259
+ # Checkpoint to the volume every few steps so a Modal preemption (spot GPU
260
+ # reclaim) resumes from the last step instead of restarting at 0. A callback
261
+ # commits the volume after each save so checkpoints survive an abrupt restart.
262
+ ckpt_dir = "/root/outputs/checkpoints"
263
+
264
+ class _CommitCheckpoint(TrainerCallback):
265
+ def on_save(self, args, state, control, **kwargs):
266
+ outputs_vol.commit()
267
+ print(f"[train] checkpoint committed @ step {state.global_step}")
268
+
269
+ trainer = Trainer(
270
+ model=model,
271
+ args=TrainingArguments(
272
+ output_dir=ckpt_dir,
273
+ per_device_train_batch_size=BATCH_SIZE,
274
+ gradient_accumulation_steps=GRAD_ACCUM,
275
+ warmup_ratio=0.05,
276
+ num_train_epochs=NUM_EPOCHS,
277
+ learning_rate=LEARNING_RATE,
278
+ lr_scheduler_type="cosine",
279
+ bf16=True,
280
+ logging_steps=10,
281
+ eval_strategy="epoch",
282
+ save_strategy="steps",
283
+ save_steps=20,
284
+ save_total_limit=1,
285
+ optim="adamw_torch",
286
+ seed=13,
287
+ report_to="none",
288
+ gradient_checkpointing=True,
289
+ gradient_checkpointing_kwargs={"use_reentrant": False},
290
+ ),
291
+ train_dataset=train_ds,
292
+ eval_dataset=val_ds,
293
+ data_collator=collator,
294
+ callbacks=[_CommitCheckpoint()],
295
+ )
296
+
297
+ # ── 3. Train (resume from last checkpoint if a preemption left one) ─────
298
+ last_ckpt = get_last_checkpoint(ckpt_dir) if os.path.isdir(ckpt_dir) else None
299
+ if last_ckpt:
300
+ print(f"[train] resuming from checkpoint: {last_ckpt}")
301
+ stats = trainer.train(resume_from_checkpoint=last_ckpt)
302
+ print(f"[train] done: {stats.metrics}")
303
+
304
+ # ── 3b. Save the LoRA adapter first + commit (cheap recovery point) ─────
305
+ # Persist the trained adapter before the merge/GGUF steps so a later failure
306
+ # never costs us the ~40 min of training again.
307
+ adapter_dir = "/root/outputs/lora_adapter"
308
+ model.save_pretrained(adapter_dir)
309
+ tokenizer.save_pretrained(adapter_dir)
310
+ outputs_vol.commit()
311
+ print(f"[train] saved LoRA adapter → {adapter_dir} (committed)")
312
+
313
+ # ── 4. Merge LoRA → 16-bit, then convert to GGUF + upload ──────────────
314
+ print("[train] merging LoRA → 16-bit safetensors")
315
+ merged = model.merge_and_unload()
316
+ _save_convert_upload(merged, tokenizer, merged_dir, gguf_dir)
317
+
318
+
319
+ @app.function(
320
+ gpu="A100-80GB",
321
+ timeout=60 * 60,
322
+ secrets=[modal.Secret.from_name("huggingface")],
323
+ volumes={"/root/.cache/huggingface": hf_cache, "/root/outputs": outputs_vol},
324
+ )
325
+ def finalize():
326
+ """Resume from the committed LoRA adapter: re-merge → GGUF → upload.
327
+
328
+ Lets us recover a completed training run without retraining (e.g. when only the
329
+ GGUF/upload tail failed). Needs a GPU because instantiating nemotron_h imports
330
+ the Triton Mamba kernels.
331
+ """
332
+ import torch
333
+ from peft import PeftModel
334
+ from transformers import AutoModelForCausalLM, AutoTokenizer
335
+
336
+ adapter_dir = "/root/outputs/lora_adapter"
337
+ merged_dir = "/root/outputs/merged_16bit"
338
+ gguf_dir = "/root/outputs/gguf"
339
+
340
+ print(f"[finalize] loading base {BASE_MODEL} + adapter {adapter_dir}")
341
+ tokenizer = AutoTokenizer.from_pretrained(adapter_dir)
342
+ base = AutoModelForCausalLM.from_pretrained(
343
+ BASE_MODEL, dtype=torch.bfloat16, low_cpu_mem_usage=True, attn_implementation="sdpa",
344
+ )
345
+ model = PeftModel.from_pretrained(base, adapter_dir)
346
+ merged = model.merge_and_unload()
347
+ _save_convert_upload(merged, tokenizer, merged_dir, gguf_dir)
348
+
349
+
350
+ @app.function(
351
+ timeout=60 * 60,
352
+ secrets=[modal.Secret.from_name("huggingface")],
353
+ volumes={"/root/outputs": outputs_vol},
354
+ )
355
+ def convert_from_merged():
356
+ """Convert an already-committed merged model → GGUF → upload. No GPU, no peft.
357
+
358
+ The fast/cheap resume path when train()'s GGUF/upload tail fails but the merged
359
+ model was committed first (it is, before the GGUF step). convert_hf_to_gguf reads
360
+ config + safetensors directly — no model instantiation, so no Mamba kernels/GPU.
361
+ """
362
+ import os
363
+
364
+ from huggingface_hub import HfApi
365
+
366
+ merged_dir = "/root/outputs/merged_16bit"
367
+ gguf_dir = "/root/outputs/gguf"
368
+ _prepare_config_for_conversion(merged_dir)
369
+ gguf_path = _convert_with_llama_cpp(merged_dir, gguf_dir)
370
+ outputs_vol.commit()
371
+ api = HfApi(token=os.environ["HF_TOKEN"])
372
+ api.create_repo(HF_REPO, repo_type="model", exist_ok=True)
373
+ api.upload_file(path_or_fileobj=gguf_path, path_in_repo=GGUF_OUTFILE,
374
+ repo_id=HF_REPO, repo_type="model")
375
+ api.upload_file(path_or_fileobj=_model_card().encode("utf-8"), path_in_repo="README.md",
376
+ repo_id=HF_REPO, repo_type="model")
377
+ print(f"[convert] uploaded {GGUF_OUTFILE} → https://huggingface.co/{HF_REPO}")
378
+
379
+
380
+ def _prepare_config_for_conversion(model_dir: str) -> None:
381
+ """Overwrite the merged config.json with the *original base* config — verbatim,
382
+ including ``auto_map`` — so llama.cpp's converter reads the right hparams.
383
+
384
+ The converter's ``load_hparams`` does ``AutoConfig.from_pretrained(
385
+ trust_remote_code=False).to_dict()``. For nemotron_h that returns NemotronHConfig
386
+ with its *class-default* MoE attributes (``num_experts_per_tok``), which makes the
387
+ converter think the dense 4B is MoE → ``KeyError: moe_intermediate_size``.
388
+
389
+ Keeping ``auto_map`` makes that AutoConfig call refuse the custom code and fall
390
+ back to the *raw* config.json — the base config, which has ``num_hidden_layers``
391
+ and ``intermediate_size`` but NO expert keys → converter takes the dense path.
392
+ (transformers 5.12's own re-save dropped ``num_hidden_layers``, so we must use the
393
+ base config, not the merged one.)
394
+ """
395
+ import json
396
+
397
+ from huggingface_hub import hf_hub_download
398
+
399
+ base_cfg = hf_hub_download(BASE_MODEL, "config.json")
400
+ data = json.loads(Path(base_cfg).read_text()) # keep auto_map intact on purpose
401
+ (Path(model_dir) / "config.json").write_text(json.dumps(data, indent=2))
402
+ print(f"[finalize] wrote verbatim base config.json (auto_map kept → raw-JSON fallback) → {model_dir}")
403
+
404
+
405
+ def _save_convert_upload(merged, tokenizer, merged_dir: str, gguf_dir: str) -> str:
406
+ """Normalize config, save merged model, convert to GGUF Q4_K_M, upload to HF.
407
+
408
+ Shared by ``train`` (in-memory merged model) and ``finalize`` (re-merged from
409
+ the committed LoRA adapter).
410
+ """
411
+ import os
412
+
413
+ from huggingface_hub import HfApi
414
+
415
+ # Nemotron ships generation_config with top_p set but do_sample=False, which
416
+ # transformers' strict save-validation rejects. Normalize to clean greedy.
417
+ gc = merged.generation_config
418
+ gc.do_sample = False
419
+ for _attr in ("top_p", "top_k", "typical_p", "temperature"):
420
+ if getattr(gc, _attr, None) is not None:
421
+ setattr(gc, _attr, None)
422
+
423
+ merged.save_pretrained(merged_dir, safe_serialization=True)
424
+ tokenizer.save_pretrained(merged_dir)
425
+ _prepare_config_for_conversion(merged_dir)
426
+ outputs_vol.commit() # persist merged model before the (fragile) GGUF step
427
+
428
+ gguf_path = _convert_with_llama_cpp(merged_dir, gguf_dir)
429
+ print(f"[finalize] GGUF ready: {gguf_path}")
430
+ outputs_vol.commit()
431
+
432
+ api = HfApi(token=os.environ["HF_TOKEN"])
433
+ api.create_repo(HF_REPO, repo_type="model", exist_ok=True)
434
+ api.upload_file(path_or_fileobj=gguf_path, path_in_repo=GGUF_OUTFILE,
435
+ repo_id=HF_REPO, repo_type="model")
436
+ api.upload_file(path_or_fileobj=_model_card().encode("utf-8"), path_in_repo="README.md",
437
+ repo_id=HF_REPO, repo_type="model")
438
+ print(f"[finalize] uploaded {GGUF_OUTFILE} → https://huggingface.co/{HF_REPO}")
439
+ return gguf_path
440
+
441
+
442
+ def _convert_with_llama_cpp(merged_dir: str, gguf_dir: str) -> str:
443
+ """Clone llama.cpp, convert merged HF model to f16 GGUF, quantize Q4_K_M.
444
+
445
+ Uses latest llama.cpp, which supports the nemotron_h architecture (NVIDIA and
446
+ others publish Nemotron-3 GGUFs built with it).
447
+ """
448
+ import shutil
449
+ import subprocess
450
+
451
+ Path(gguf_dir).mkdir(parents=True, exist_ok=True)
452
+
453
+ # Commit-specific path so a stale clone in a reused (warm) Modal container can't
454
+ # be mistaken for the pinned version — that bug skipped the checkout and used an
455
+ # old converter that misclassified the dense 4B as MoE.
456
+ llama_dir = f"/root/llama.cpp-{LLAMA_CPP_COMMIT[:8]}"
457
+ quantize_bin = f"{llama_dir}/build/bin/llama-quantize"
458
+ convert_py = f"{llama_dir}/convert_hf_to_gguf.py"
459
+
460
+ if not Path(quantize_bin).exists():
461
+ if Path(llama_dir).exists():
462
+ shutil.rmtree(llama_dir)
463
+ subprocess.run(["git", "clone", "https://github.com/ggml-org/llama.cpp", llama_dir], check=True)
464
+ # Pin to a commit whose converter has the nemotron_h dense/MoE split.
465
+ subprocess.run(["git", "-C", llama_dir, "checkout", LLAMA_CPP_COMMIT], check=True)
466
+ # NOTE: deliberately NOT `pip install -r requirements.txt` — it downgrades our
467
+ # transformers below nemotron_h support. The convert deps are already in the image.
468
+ subprocess.run(["cmake", "-S", llama_dir, "-B", f"{llama_dir}/build", "-DLLAMA_CURL=OFF"], check=True)
469
+ subprocess.run(["cmake", "--build", f"{llama_dir}/build", "--target", "llama-quantize", "-j"], check=True)
470
+
471
+ # Force the DENSE path (idempotent — run every call, NOT just on fresh clone, since
472
+ # a warm container may already have the built dir and skip the block above).
473
+ # transformers' NemotronHConfig always carries a default num_experts_per_tok=2, so
474
+ # the converter's `if has_moe_params` always trips and treats our dense 4B as MoE
475
+ # (→ KeyError moe_intermediate_size, and a broken empty-FFN GGUF). The 4B has no
476
+ # experts, so disabling that branch is correct.
477
+ subprocess.run(
478
+ ["sed", "-i", "s/if has_moe_params:/if False: # CityQuest: dense nemotron_h/",
479
+ f"{llama_dir}/conversion/nemotron.py"],
480
+ check=True,
481
+ )
482
+
483
+ f16 = f"{gguf_dir}/model-f16.gguf"
484
+ subprocess.run(
485
+ ["python", convert_py, merged_dir, "--outfile", f16, "--outtype", "f16"],
486
+ check=True,
487
+ )
488
+ out = f"{gguf_dir}/{GGUF_OUTFILE}"
489
+ subprocess.run([quantize_bin, f16, out, "Q4_K_M"], check=True)
490
+ return out
491
+
492
+
493
+ def _model_card() -> str:
494
+ return f"""---
495
+ base_model: {BASE_MODEL}
496
+ library_name: gguf
497
+ tags:
498
+ - cityquest
499
+ - nemotron
500
+ - game-generation
501
+ - llama.cpp
502
+ ---
503
+
504
+ # CityQuest Nemotron 3 Nano 4B (Q4_K_M GGUF)
505
+
506
+ LoRA fine-tune of `{BASE_MODEL}` on the CityQuest location-based game dataset
507
+ (~840 train / 92 val examples across scavenger hunt, hide-and-seek and tag).
508
+
509
+ Trained to emit games directly in the app's `game_schema.json` contract
510
+ (non-reasoning / JSON-only). Drop-in replacement for the stock Nemotron GGUF in
511
+ `app/services/generator.py`.
512
+
513
+ - LoRA r={LORA_R}, alpha={LORA_ALPHA}, epochs={NUM_EPOCHS}, lr={LEARNING_RATE}
514
+ - Loaded via native `transformers` (arch `nemotron_h`); MoE router / lm_head excluded
515
+ - Quantization: Q4_K_M · File: `{GGUF_OUTFILE}`
516
+ """
517
+
518
+
519
+ @app.function(
520
+ image=eval_image,
521
+ gpu="A100",
522
+ timeout=60 * 60,
523
+ secrets=[modal.Secret.from_name("huggingface")],
524
+ volumes={"/root/.cache/huggingface": hf_cache},
525
+ )
526
+ def evaluate(repo: str, file: str, limit: int = 0) -> dict:
527
+ """Run val prompts through a GGUF model and report JSON-parse / schema-pass rates.
528
+
529
+ Runs on GPU in eval_image (llama.cpp), so it works even though the dev Codespace
530
+ has no llama.cpp. Returns a metrics dict and logs a summary.
531
+ """
532
+ import json
533
+
534
+ import jsonschema
535
+ from llama_cpp import Llama
536
+
537
+ def extract_json(text: str):
538
+ start = text.find("{")
539
+ if start == -1:
540
+ return None
541
+ depth = 0
542
+ for i in range(start, len(text)):
543
+ if text[i] == "{":
544
+ depth += 1
545
+ elif text[i] == "}":
546
+ depth -= 1
547
+ if depth == 0:
548
+ raw = text[start:i + 1]
549
+ if raw.startswith("{{") and raw.endswith("}}"):
550
+ raw = raw[1:-1]
551
+ return raw
552
+ return None
553
+
554
+ schema = json.loads(Path(REMOTE_SCHEMA).read_text())
555
+ rows = [json.loads(l) for l in Path(f"{REMOTE_DATA}/val.jsonl").read_text().splitlines() if l.strip()]
556
+ if limit:
557
+ rows = rows[:limit]
558
+
559
+ print(f"[eval] {repo}/{file} — loading")
560
+ llm = Llama.from_pretrained(repo_id=repo, filename=file, n_ctx=8192, n_gpu_layers=-1, verbose=False)
561
+
562
+ parsed_ok = schema_ok = 0
563
+ for row in rows:
564
+ messages = [m for m in row["messages"] if m["role"] in ("system", "user")]
565
+ result = llm.create_chat_completion(
566
+ messages=messages, max_tokens=8192, temperature=0.3, top_p=0.9, stop=["```"],
567
+ )
568
+ text = result["choices"][0]["message"]["content"].strip()
569
+ js = extract_json(text)
570
+ if not js:
571
+ continue
572
+ try:
573
+ game = json.loads(js)
574
+ except json.JSONDecodeError:
575
+ continue
576
+ parsed_ok += 1
577
+ try:
578
+ jsonschema.validate(instance=game, schema=schema)
579
+ schema_ok += 1
580
+ except jsonschema.ValidationError:
581
+ pass
582
+
583
+ n = len(rows)
584
+ metrics = {
585
+ "model": f"{repo}/{file}",
586
+ "n": n,
587
+ "json_parse_rate": round(100 * parsed_ok / n, 1),
588
+ "schema_pass_rate": round(100 * schema_ok / n, 1),
589
+ }
590
+ print(f"[eval] {metrics['model']}: parse={metrics['json_parse_rate']}% "
591
+ f"schema={metrics['schema_pass_rate']}% (n={n})")
592
+ return metrics
593
+
594
+
595
+ @app.local_entrypoint()
596
+ def main(eval_baseline: bool = True, eval_limit: int = 0):
597
+ """Train + upload, then evaluate the fine-tuned model (and baseline) on the val set."""
598
+ train.remote()
599
+ print("\n=== Evaluation ===")
600
+ tuned = evaluate.remote(HF_REPO, GGUF_OUTFILE, eval_limit)
601
+ print(f"Fine-tuned : schema {tuned['schema_pass_rate']}% parse {tuned['json_parse_rate']}%")
602
+ if eval_baseline:
603
+ base = evaluate.remote(BASELINE_REPO, BASELINE_FILE, eval_limit)
604
+ print(f"Baseline : schema {base['schema_pass_rate']}% parse {base['json_parse_rate']}%")
605
+ verdict = ("PASS — safe to swap" if tuned["schema_pass_rate"] >= base["schema_pass_rate"]
606
+ else "REGRESSION — do not swap")
607
+ print(f"Gate: fine-tuned >= baseline ? {verdict}")
608
+
609
+
610
+ @app.local_entrypoint()
611
+ def convert_only():
612
+ """Convert+upload from the committed merged model (no GPU, no peft).
613
+
614
+ modal run --detach training/train_modal.py::convert_from_merged
615
+ """
616
+ convert_from_merged.remote()
617
+
618
+
619
+ @app.local_entrypoint()
620
+ def eval_only(repo: str = HF_REPO, file: str = GGUF_OUTFILE, limit: int = 0):
621
+ """Evaluate an already-uploaded GGUF without retraining.
622
+
623
+ Example:
624
+ modal run training/train_modal.py::eval_only
625
+ modal run training/train_modal.py::eval_only --repo nvidia/... --file ....gguf
626
+ """
627
+ print(evaluate.remote(repo, file, limit))