sarathi-balakrishnan commited on
Commit
1d7909c
·
verified ·
1 Parent(s): 47ad549

Revise model card: correct numbers and license, remove unmeasured claims, add limitations

Browse files
Files changed (1) hide show
  1. README.md +103 -598
README.md CHANGED
@@ -1,669 +1,174 @@
1
  ---
2
- license: mit
3
  language:
4
  - en
5
  tags:
6
  - agriculture
7
  - business-intelligence
8
- - b2b
9
- - fine-tuned
10
  - llama
11
  - llama-3.1
12
  - lora
13
  - peft
14
  - knowledge-distillation
15
- - multi-teacher
16
- - claude
17
- - gpt-4
18
  library_name: peft
19
  base_model: meta-llama/Llama-3.1-8B-Instruct
20
- datasets:
21
- - custom
22
  pipeline_tag: text-generation
23
- model-index:
24
- - name: llama-agri-b2b-intelligence
25
- results:
26
- - task:
27
- type: text-generation
28
- name: Agricultural B2B Analysis
29
- dataset:
30
- type: custom
31
- name: Agricultural B2B Intelligence Dataset
32
- metrics:
33
- - type: train_loss
34
- value: 0.70
35
- name: Final Training Loss
36
- - type: eval_loss
37
- value: 0.78
38
- name: Final Evaluation Loss
39
- - type: training_time
40
- value: 55
41
- name: Training Hours
42
  ---
43
 
44
- # Agricultural B2B Intelligence Model
45
 
46
- <div align="center">
47
 
48
- ![Version](https://img.shields.io/badge/version-1.0.0-blue)
49
- ![License](https://img.shields.io/badge/license-MIT-green)
50
- ![Model Size](https://img.shields.io/badge/parameters-8B-orange)
51
- ![Training Hours](https://img.shields.io/badge/training-55%20hours-purple)
52
 
53
- **A production-grade language model fine-tuned for agricultural business intelligence, built using multi-teacher knowledge distillation from Claude Sonnet 4 and GPT-4.1**
54
 
55
- [Model Card](#model-details) | [Usage](#usage) | [Training Journey](#the-journey) | [Metrics](#training-metrics) | [API](#api-usage)
56
 
57
- </div>
 
 
 
 
 
 
 
 
 
 
58
 
59
- ---
60
-
61
- ## Executive Summary
62
-
63
- This model represents a breakthrough in agricultural AI - distilling the combined knowledge of two frontier AI models (Claude Sonnet 4 and GPT-4.1) into a compact, deployable 8B parameter model. After **55+ hours of training** on **10,000 expert-crafted examples**, this model delivers expert-level agricultural business intelligence for B2B companies serving farmers and ranchers across all 50 US states.
64
-
65
- ```
66
- ┌─────────────────────────────────────────────────────────────────────────────┐
67
- │ MULTI-TEACHER KNOWLEDGE DISTILLATION │
68
- ├─────────────────────────────────────────────────────────────────────────────┤
69
- │ │
70
- │ ┌──────────────────────┐ ┌──────────────────────┐ │
71
- │ │ TEACHER 1 │ │ TEACHER 2 │ │
72
- │ │ Claude Sonnet 4 │ │ GPT-4.1 │ │
73
- │ │ 5,007 responses │ │ 4,993 responses │ │
74
- │ │ ~$100 API cost │ │ ~$80 API cost │ │
75
- │ └──────────┬───────────┘ └──────────┬───────────┘ │
76
- │ │ │ │
77
- │ └─────────────┬─────────────────────┘ │
78
- │ │ │
79
- │ ▼ │
80
- │ ┌─────────────────────────┐ │
81
- │ │ STUDENT MODEL │ │
82
- │ │ Llama 3.1 8B Instruct │ │
83
- │ │ LoRA Fine-tuned │ │
84
- │ │ 55 hours training │ │
85
- │ └─────────────────────────┘ │
86
- │ │
87
- └─────────────────────────────────────────────────────────────────────────────┘
88
- ```
89
-
90
- ---
91
-
92
- ## The Journey: From Phi-3 to Llama 3.1
93
-
94
- ### The Evolution of Our Student Model Selection
95
-
96
- This project went through several iterations before arriving at the optimal architecture. Here's the complete story:
97
-
98
- #### Phase 1: Phi-3 Mini (Abandoned)
99
- **Initial Consideration:** Microsoft's Phi-3 Mini (3.8B parameters)
100
- - **Pros:** Small, fast, efficient
101
- - **Cons:** Limited context window, struggled with complex agricultural terminology
102
- - **Decision:** Too small for the domain complexity required
103
-
104
- #### Phase 2: Qwen 2.5 7B (Temporary)
105
- **Second Attempt:** Alibaba's Qwen 2.5-7B-Instruct
106
- - **Pros:** Open weights, good multilingual support, strong reasoning
107
- - **Cons:** Less optimized for English-only use case, licensing considerations for commercial use
108
- - **Status:** Used temporarily while awaiting Llama access approval
109
- - **Why we moved on:** Meta's Llama offered better ecosystem support and commercial licensing
110
-
111
- #### Phase 3: Llama 3.1 8B Instruct (Final Selection)
112
- **Final Choice:** Meta's Llama 3.1-8B-Instruct
113
- - **Pros:**
114
- - Excellent instruction following
115
- - Strong reasoning capabilities
116
- - Permissive license for commercial use
117
- - Large community and ecosystem
118
- - Optimized for chat/instruct use cases
119
- - Native support for long contexts (128K)
120
- - **Cons:** Gated model requiring license approval
121
- - **Decision:** Best balance of capability, licensing, and community support
122
-
123
- ### Why Multi-Teacher Distillation?
124
-
125
- Traditional fine-tuning uses a single data source. We pioneered a **multi-teacher approach**:
126
-
127
- | Aspect | Single Teacher | Multi-Teacher (Our Approach) |
128
- |--------|----------------|------------------------------|
129
- | Diversity | Limited perspective | Complementary viewpoints |
130
- | Robustness | May inherit biases | Cross-validated knowledge |
131
- | Coverage | Gaps in knowledge | Comprehensive coverage |
132
- | Quality | Single style | Best of both worlds |
133
-
134
- **Claude Sonnet 4** excels at:
135
- - Structured, methodical analysis
136
- - Nuanced risk assessment
137
- - Detailed data interpretation
138
 
139
- **GPT-4.1** excels at:
140
- - Creative market insights
141
- - Trend identification
142
- - Actionable recommendations
 
 
 
 
143
 
144
- By combining both, our student model inherits the **strengths of each teacher** while mitigating individual weaknesses.
 
 
 
145
 
146
- ---
147
-
148
- ## Training Infrastructure
149
-
150
- ### Hardware Configuration
151
-
152
- ```
153
- ┌─────────────────────────────────────────────────────────┐
154
- │ NVIDIA DGX SPARK WORKSTATION │
155
- ├─────────────────────────────────────────────────────────┤
156
- │ GPU: NVIDIA GB10 (Blackwell Architecture) │
157
- │ VRAM: 128 GB Unified Memory │
158
- │ RAM: 128 GB System Memory │
159
- │ Storage: 4 TB NVMe SSD │
160
- │ OS: Ubuntu Linux │
161
- └─────────────────────────────────────────────────────────┘
162
- ```
163
-
164
- ### Why Blackwell GPU?
165
-
166
- The NVIDIA Blackwell GB10 represents the cutting edge of AI training hardware:
167
- - **BF16 Native Support:** Optimal precision for LLM training
168
- - **Unified Memory:** 128GB allows full model + gradients in memory
169
- - **Tensor Cores:** 5th generation for maximum throughput
170
- - **Energy Efficiency:** Lower power consumption than previous generations
171
-
172
- ---
173
 
174
- ## Complete Pipeline Timeline
 
 
 
 
 
 
175
 
176
- ### Total Project Duration: ~70 Hours
177
-
178
- ```
179
- Phase Duration Status
180
- ─────────────────────────────────────────────────
181
- 1. Environment Setup 30 min ✅ Complete
182
- 2. Knowledge Base Creation 45 min ✅ Complete
183
- 3. Query Generation 20 min ✅ Complete
184
- 4. Teacher Response Gen 8 hours ✅ Complete
185
- ├─ Claude Sonnet 4 4.5 hrs (5,007 responses)
186
- └─ GPT-4.1 3.5 hrs (4,993 responses)
187
- 5. Dataset Preparation 15 min ✅ Complete
188
- 6. Model Fine-tuning 55 hours ✅ Complete
189
- ├─ Epoch 1 18.5 hrs
190
- ├─ Epoch 2 18.5 hrs
191
- └─ Epoch 3 18.0 hrs
192
- 7. Benchmarking 30 min ⏳ Pending
193
- 8. HuggingFace Upload 10 min ⏳ Pending
194
- ─────────────────────────────────────────────────
195
- TOTAL ~70 hours
196
- ```
197
-
198
- ---
199
-
200
- ## Training Metrics
201
-
202
- ### Loss Progression Across Epochs
203
-
204
- ```
205
- Loss
206
- │
207
- 1.8 ┤ ●
208
- │ ╲
209
- 1.6 ┤ ╲
210
- │ ╲
211
- 1.4 ┤ ╲
212
- │ ╲
213
- 1.2 ┤ ●
214
- │ ╲
215
- 1.0 ┤ ●──●
216
- │ ╲
217
- 0.8 ┤ ●──●──●──●──●──●──●──●
218
- │ EPOCH 1 │ EPOCH 2 │ EPOCH 3
219
- 0.6 ┤
220
- │
221
- 0.4 ┼────┬────┬────┬────┬────┬────┬────┬────┬────
222
- 0 100 200 300 400 500 600 700 800
223
- Steps
224
- ```
225
-
226
- ### Detailed Epoch Metrics
227
-
228
- | Metric | Epoch 1 | Epoch 2 | Epoch 3 | Improvement |
229
- |--------|---------|---------|---------|-------------|
230
- | **Training Loss** | 0.89 | 0.77 | ~0.70 | **-21%** |
231
- | **Eval Loss** | 0.87 | 0.82 | ~0.78 | **-10%** |
232
- | **Steps** | 266 | 532 | 798 | - |
233
- | **Duration** | 18.5 hrs | 18.5 hrs | 18 hrs | - |
234
- | **Learning Rate** | 5e-5 → 4.1e-5 | 4.1e-5 → 1.6e-5 | 1.6e-5 → 0 | Cosine decay |
235
-
236
- ### Training Configuration
237
 
238
  ```python
239
- # LoRA Configuration
240
- LORA_CONFIG = {
241
- "r": 128, # High rank for complex domain
242
- "lora_alpha": 256, # 2x rank for stable training
243
- "target_modules": [
244
- "q_proj", "k_proj", "v_proj", "o_proj",
245
- "gate_proj", "up_proj", "down_proj"
246
- ],
247
- "lora_dropout": 0.05,
248
- "bias": "none",
249
- "task_type": "CAUSAL_LM"
250
- }
251
-
252
- # Training Configuration
253
- TRAINING_CONFIG = {
254
- "num_train_epochs": 3,
255
- "per_device_train_batch_size": 2,
256
- "gradient_accumulation_steps": 16, # Effective batch = 32
257
- "learning_rate": 5e-5,
258
- "warmup_ratio": 0.1,
259
- "lr_scheduler_type": "cosine",
260
- "bf16": True,
261
- "gradient_checkpointing": True,
262
- "max_seq_length": 4096
263
- }
264
- ```
265
-
266
- ### Parameter Efficiency
267
-
268
- | Metric | Value |
269
- |--------|-------|
270
- | Base Model Parameters | 8,030,261,248 (8.03B) |
271
- | LoRA Trainable Parameters | 167,772,160 (168M) |
272
- | **Trainable Ratio** | **2.09%** |
273
- | Memory Usage | ~45 GB VRAM |
274
- | Training Throughput | ~4 min/step |
275
-
276
- ---
277
-
278
- ## Dataset Composition
279
-
280
- ### Knowledge Base Coverage
281
-
282
- ```
283
- ┌─────────────────────────────────────────────────────────┐
284
- │ COMPREHENSIVE US AGRICULTURAL DATA │
285
- ├─────────────────────────────────────────────────────────┤
286
- │ │
287
- │ 🗺️ Geographic Coverage │
288
- │ ├── States: 50 (All US states) │
289
- │ ├── Counties: 3,142 (99.9% coverage) │
290
- │ ├── Zipcodes: 2,000 (Key agricultural areas) │
291
- │ └── Regions: All USDA Farm Resource Regions │
292
- │ │
293
- │ 🌾 Agricultural Data │
294
- │ ├── Crops: 12 major commodities │
295
- │ ├── Livestock: 8 categories │
296
- │ └── Markets: 15 commodity markets │
297
- │ │
298
- │ 🏢 Industry Coverage │
299
- │ └── B2B Sectors: 8 specialized industries │
300
- │ │
301
- └─────────────────────────────────────────────────────────┘
302
- ```
303
-
304
- ### Query Distribution (10,000 Total)
305
-
306
- | Category | Count | Percentage | Description |
307
- |----------|-------|------------|-------------|
308
- | County Intelligence | 3,000 | 30% | Deep county-level analysis |
309
- | Zipcode Analysis | 1,500 | 15% | Granular local insights |
310
- | Market Intelligence | 1,000 | 10% | Market trends and opportunities |
311
- | State Analysis | 1,000 | 10% | State-wide agricultural overview |
312
- | Risk Assessment | 800 | 8% | Risk evaluation and mitigation |
313
- | B2B Marketing | 800 | 8% | Go-to-market strategies |
314
- | Predictions | 600 | 6% | Future trend forecasting |
315
- | Historical Trends | 600 | 6% | Historical data analysis |
316
- | Commodity Analysis | 400 | 4% | Commodity-specific insights |
317
- | Comparative Analysis | 300 | 3% | Cross-region comparisons |
318
-
319
- ### Teacher Response Statistics
320
-
321
- | Teacher | Responses | Avg Length | Avg Time | Total Cost |
322
- |---------|-----------|------------|----------|------------|
323
- | Claude Sonnet 4 | 5,007 | ~1,200 tokens | 4.2s | ~$100 |
324
- | GPT-4.1 | 4,993 | ~1,100 tokens | 2.8s | ~$80 |
325
- | **Combined** | **10,000** | ~1,150 tokens | 3.5s | **~$180** |
326
-
327
- ### Data Split
328
-
329
- ```
330
- Training: 8,500 examples (85%) ████████████████░░
331
- Validation: 1,000 examples (10%) ██░░░░░░░░░░░░░░░░
332
- Test: 500 examples (5%) █░░░░░░░░░░░░░░░░░
333
- ─────────────────────────────────────────────────────
334
- Total: 10,000 examples
335
- ```
336
-
337
- ---
338
-
339
- ## Target Industries & Use Cases
340
-
341
- ### Supported B2B Sectors
342
-
343
- | Industry | Primary Use Cases | Key Metrics Provided |
344
- |----------|-------------------|----------------------|
345
- | **Crop Insurance** | Risk assessment, premium pricing, loss prediction | Historical loss ratios, weather risk scores, yield variability |
346
- | **Farm Equipment** | Market sizing, dealer network, territory planning | Equipment penetration, farm size distribution, mechanization rates |
347
- | **Seed & Genetics** | Variety placement, market penetration, climate zones | Seed market share, variety performance, adoption curves |
348
- | **Fertilizer & Soil** | Demand forecasting, logistics, pricing | Soil types, nutrient needs, application rates |
349
- | **Pesticides** | Application timing, resistance patterns, compliance | Pest pressure maps, resistance tracking, regulatory status |
350
- | **Irrigation** | Water management, system sizing, ROI analysis | Water availability, irrigation penetration, efficiency metrics |
351
- | **Agricultural Lending** | Farm credit risk, land valuation, cash flow | Debt ratios, land values, income stability |
352
- | **Land Brokerage** | Parcel analysis, comparable sales, investment returns | Price per acre trends, transaction volumes, cap rates |
353
-
354
- ---
355
-
356
- ## Model Capabilities
357
-
358
- ### What This Model Can Do
359
-
360
- ✅ **Geographic Analysis**
361
- - State-level agricultural overviews
362
- - County-level deep dives
363
- - Zipcode-level granular insights
364
- - Cross-region comparisons
365
-
366
- ✅ **Market Intelligence**
367
- - Market entry analysis
368
- - Competitive landscape mapping
369
- - Opportunity identification
370
- - Risk factor assessment
371
-
372
- ✅ **Business Strategy**
373
- - Go-to-market recommendations
374
- - Territory planning
375
- - Customer segmentation
376
- - Pricing strategy insights
377
-
378
- ✅ **Data Synthesis**
379
- - USDA data interpretation
380
- - Trend analysis
381
- - Predictive insights
382
- - Historical pattern recognition
383
-
384
- ### Output Format
385
-
386
- The model generates structured analysis following this format:
387
-
388
- ```markdown
389
- ## Executive Summary
390
- [2-3 sentence high-level overview]
391
-
392
- ## Geographic/Market Profile
393
- [Key statistics and characteristics]
394
-
395
- ## Analysis
396
- [Detailed data-driven insights with specific metrics]
397
-
398
- ## Opportunities
399
- [Specific actionable opportunities ranked by potential]
400
-
401
- ## Risk Factors
402
- [Challenges, constraints, and mitigation strategies]
403
-
404
- ## Recommendations
405
- [Prioritized action items with implementation guidance]
406
-
407
- ## Confidence Level
408
- [High/Medium/Low with reasoning and data quality notes]
409
-
410
- ## Data Sources
411
- [Referenced USDA and industry sources]
412
- ```
413
-
414
- ---
415
 
416
  ## Usage
417
 
418
- ### Quick Start
419
-
420
  ```python
421
  from transformers import AutoTokenizer, AutoModelForCausalLM
422
  from peft import PeftModel
423
  import torch
424
 
425
- # Load model
426
  base_model_name = "meta-llama/Llama-3.1-8B-Instruct"
427
  adapter_name = "sarathi-balakrishnan/llama-agri-b2b-intelligence"
428
 
429
  tokenizer = AutoTokenizer.from_pretrained(base_model_name)
430
  base_model = AutoModelForCausalLM.from_pretrained(
431
- base_model_name,
432
- torch_dtype=torch.bfloat16,
433
- device_map="auto"
434
  )
435
  model = PeftModel.from_pretrained(base_model, adapter_name)
436
 
437
- # Generate analysis
438
  messages = [
439
- {
440
- "role": "system",
441
- "content": "You are an expert agricultural business intelligence analyst."
442
- },
443
- {
444
- "role": "user",
445
- "content": "Analyze Iowa's corn market for a seed company evaluating expansion."
446
- }
447
  ]
448
-
449
  text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
450
  inputs = tokenizer(text, return_tensors="pt").to(model.device)
451
 
452
- outputs = model.generate(
453
- inputs["input_ids"],
454
- max_new_tokens=1500,
455
- temperature=0.7,
456
- do_sample=True
457
- )
458
-
459
- response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
460
- print(response)
461
  ```
462
 
463
- ### Merging LoRA Weights (Optional)
464
-
465
- For faster inference, merge the LoRA adapters:
466
 
467
  ```python
468
- # Merge and save
469
- merged_model = model.merge_and_unload()
470
- merged_model.save_pretrained("./llama-agri-merged")
471
  tokenizer.save_pretrained("./llama-agri-merged")
472
  ```
473
 
474
- ### Recommended Generation Parameters
475
-
476
- ```python
477
- generation_config = {
478
- "max_new_tokens": 1500, # Sufficient for detailed analysis
479
- "temperature": 0.7, # Balanced creativity/consistency
480
- "top_p": 0.9, # Nucleus sampling
481
- "repetition_penalty": 1.1, # Reduce repetition
482
- "do_sample": True
483
- }
484
- ```
485
-
486
- ---
487
 
488
- ## Example Outputs
489
-
490
- ### Example 1: County-Level Analysis
491
-
492
- **Query:** "Analyze agricultural opportunities in Fresno County, California for a precision agriculture company."
493
-
494
- **Response:**
495
- ```markdown
496
- ## Executive Summary
497
- Fresno County represents one of the nation's most valuable agricultural markets,
498
- with over $7.5 billion in annual agricultural output. The combination of diverse
499
- crop production, large farm operations, and water management challenges creates
500
- significant opportunities for precision agriculture solutions.
501
-
502
- ## Geographic Profile
503
- - **Location:** Central San Joaquin Valley, California
504
- - **Agricultural Acres:** 1.9 million acres
505
- - **Top Crops:** Almonds, grapes, tomatoes, cotton, citrus
506
- - **Farm Count:** ~6,000 operations
507
- - **Average Farm Size:** 315 acres
508
-
509
- ## Analysis
510
- Fresno County leads California in agricultural production value. Key factors:
511
-
512
- 1. **Crop Diversity:** 350+ commodities grown commercially
513
- 2. **Irrigation Dependency:** 95% of farmland irrigated
514
- 3. **Water Stress:** Ongoing groundwater sustainability concerns
515
- 4. **Technology Adoption:** 35% precision ag penetration (below potential)
516
-
517
- ## Opportunities
518
- 1. **Water Management Solutions** (High Priority)
519
- - Soil moisture monitoring: $15M addressable market
520
- - Variable rate irrigation: Growing 25% annually
521
-
522
- 2. **Specialty Crop Analytics**
523
- - Tree nut optimization: 500,000+ almond acres
524
- - Vineyard management: 180,000 grape acres
525
-
526
- ## Risk Factors
527
- - Water availability regulations (SGMA compliance)
528
- - Labor cost pressures driving automation
529
- - Climate variability affecting crop selection
530
-
531
- ## Recommendations
532
- 1. Partner with irrigation districts for pilot programs
533
- 2. Focus initial sales on almond and grape operations (highest ROI)
534
- 3. Develop Spanish-language support (40% Hispanic farm operators)
535
-
536
- ## Confidence Level
537
- **High** - Based on USDA Census of Agriculture, California Department of
538
- Food and Agriculture data, and established market trends.
539
- ```
540
-
541
- ---
542
 
543
  ## Limitations
544
 
545
- ### Known Limitations
546
-
547
- 1. **Geographic Scope:** Focused exclusively on US agricultural markets
548
- 2. **Data Currency:** Training data reflects knowledge up to early 2025
549
- 3. **Synthetic Training:** Responses generated by AI teachers, not human experts
550
- 4. **Specificity:** May lack hyperlocal details for small rural communities
551
- 5. **Numerical Precision:** Statistics should be verified against official sources
552
 
553
- ### When NOT to Use This Model
554
 
555
- - For official regulatory compliance decisions
556
- - As sole source for financial investment decisions
557
- - For real-time commodity trading signals
558
- - To replace professional agricultural consultants for high-stakes decisions
559
-
560
- ### Recommended Usage
561
-
562
- This model is best used as:
563
- - A starting point for market research
564
- - A tool for generating initial analysis frameworks
565
- - A complement to (not replacement for) professional expertise
566
- - A rapid prototyping tool for agricultural B2B applications
567
-
568
- ---
569
 
570
- ## Technical Specifications
571
-
572
- ### Model Architecture
573
-
574
- | Component | Specification |
575
- |-----------|---------------|
576
- | Base Model | Llama 3.1 8B Instruct |
577
- | Architecture | Transformer (decoder-only) |
578
- | Parameters | 8.03B (base) + 168M (LoRA) |
579
- | Context Length | 4,096 tokens (training) / 128K (inference) |
580
- | Vocabulary | 128,256 tokens |
581
- | Precision | BF16 |
582
-
583
- ### LoRA Adapter Details
584
-
585
- | Parameter | Value |
586
- |-----------|-------|
587
- | Rank (r) | 128 |
588
- | Alpha | 256 |
589
- | Dropout | 0.05 |
590
- | Target Modules | q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj |
591
- | Trainable Parameters | 167,772,160 |
592
-
593
- ### Files Included
594
-
595
- ```
596
- llama-agri-b2b-intelligence/
597
- ├── README.md # This file
598
- ├── adapter_config.json # LoRA configuration
599
- ├── adapter_model.safetensors # LoRA weights
600
- ├── tokenizer_config.json # Tokenizer settings
601
- ├── special_tokens_map.json # Special tokens
602
- └── tokenizer.json # Full tokenizer
603
- ```
604
-
605
- ---
606
-
607
- ## Data Sources Referenced in Training
608
-
609
- The training data incorporates knowledge from:
610
 
611
- - **USDA NASS** - National Agricultural Statistics Service
612
- - **USDA ERS** - Economic Research Service
613
- - **FSA** - Farm Service Agency (subsidies, programs)
614
- - **RMA** - Risk Management Agency (crop insurance)
615
- - **SSURGO** - Soil Survey Geographic Database
616
- - **CDL** - Cropland Data Layer
617
- - **CME Group** - Commodity futures data
618
-
619
- ---
620
 
621
  ## Citation
622
 
623
  ```bibtex
624
- @misc{llama-agri-b2b-intelligence-2024,
625
- title={Agricultural B2B Intelligence: Multi-Teacher Knowledge Distillation
626
- for Domain-Specific Large Language Models},
627
- author={Sarathi Balakrishnan},
628
- year={2024},
629
- publisher={HuggingFace},
630
- url={https://huggingface.co/sarathi-balakrishnan/llama-agri-b2b-intelligence},
631
- note={Fine-tuned using Claude Sonnet 4 and GPT-4.1 as teachers on
632
- NVIDIA DGX Spark with Blackwell GPU}
633
  }
634
  ```
635
-
636
- ---
637
-
638
- ## License
639
-
640
- **MIT License** - Free for commercial and research use.
641
-
642
- This model is released under the MIT license. The base Llama 3.1 model is subject to Meta's Llama 3.1 Community License Agreement.
643
-
644
- ---
645
-
646
- ## Acknowledgments
647
-
648
- - **Meta AI** - For the Llama 3.1 base model
649
- - **Anthropic** - For Claude Sonnet 4 teacher responses
650
- - **OpenAI** - For GPT-4.1 teacher responses
651
- - **NVIDIA** - For DGX Spark infrastructure
652
- - **Hugging Face** - For PEFT library and model hosting
653
-
654
- ---
655
-
656
- ## Contact & Support
657
-
658
- - **HuggingFace:** [@sarathi-balakrishnan](https://huggingface.co/sarathi-balakrishnan)
659
- - **GitHub:** [@sarathi-aiml](https://github.com/sarathi-aiml)
660
-
661
- ---
662
-
663
- <div align="center">
664
-
665
- **Built with multi-teacher knowledge distillation**
666
-
667
- *Transforming frontier AI capabilities into deployable agricultural intelligence*
668
-
669
- </div>
 
1
  ---
2
+ license: llama3.1
3
  language:
4
  - en
5
  tags:
6
  - agriculture
7
  - business-intelligence
 
 
8
  - llama
9
  - llama-3.1
10
  - lora
11
  - peft
12
  - knowledge-distillation
13
+ - sequence-level-distillation
14
+ - synthetic-data
15
+ - experiment
16
  library_name: peft
17
  base_model: meta-llama/Llama-3.1-8B-Instruct
 
 
18
  pipeline_tag: text-generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  ---
20
 
21
+ # Llama 3.1 8B — Agricultural B2B Intelligence (LoRA adapter, experiment)
22
 
23
+ **Built with Llama.**
24
 
25
+ > **Personal experiment** (December 2025). This LoRA adapter for Llama-3.1-8B-Instruct was trained
26
+ > on 10,000 agricultural business-analysis answers produced by two commercial LLMs. It is a
27
+ > study of **sequence-level knowledge distillation**: supervised fine-tuning on teacher outputs.
28
+ > So far it has been evaluated only by training and validation loss. **No task benchmark has been run yet.**
29
 
30
+ Merged-weights version: [llama-agri-b2b-intelligence-merged](https://huggingface.co/sarathi-balakrishnan/llama-agri-b2b-intelligence-merged)
31
 
32
+ ## Summary
33
 
34
+ | | |
35
+ |---|---|
36
+ | Base model | `meta-llama/Llama-3.1-8B-Instruct` (8.03B) |
37
+ | Method | LoRA SFT on teacher-generated responses (sequence-level distillation) |
38
+ | Teacher outputs | 5,007 from Claude Sonnet 4, 4,993 from GPT-4.1 (10,000 total, ~1,150 tokens avg) |
39
+ | Split | 8,500 train / 1,000 validation / 500 test (test set not yet used) |
40
+ | LoRA | r = 128, α = 256, dropout 0.05, all 7 projections in every layer |
41
+ | Trainable parameters | **335,544,320** (≈4.18% of 8.03B) |
42
+ | Adapter file | 1.34 GB (`adapter_model.safetensors`, FP32) |
43
+ | Hardware / time | 1× NVIDIA DGX Spark (GB10), ~55 h for 3 epochs (798 steps, ~4 min/step, ~45 GB memory) |
44
+ | Evaluation | Loss only. Benchmark **pending** |
45
 
46
+ ## How the data was made
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ 1. I built a knowledge base and a query generator for US agricultural regions and B2B sectors
49
+ (crop insurance, equipment, seed, fertilizer, crop protection, irrigation, lending, land brokerage).
50
+ 2. I generated 10,000 queries. The mix: county 30%, zip code 15%, market 10%, state 10%, risk 8%,
51
+ B2B marketing 8%, predictions 6%, historical trends 6%, commodity 4%, comparative 3%.
52
+ 3. Each query was sent once to **one** teacher through the providers' APIs. That gave 5,007 Claude Sonnet 4
53
+ responses (~$100 of API usage) and 4,993 GPT-4.1 responses (~$80).
54
+ 4. The student was fine-tuned with standard next-token cross-entropy on those responses. No teacher logits
55
+ were used (they aren't available from these APIs), so this is sequence-level KD, not logit/KL distillation.
56
 
57
+ **About the teacher data.** The training targets are outputs from third-party models. Anyone using this
58
+ adapter or its data is also subject to the terms of the providers whose models generated those
59
+ outputs (Anthropic and OpenAI), in addition to the Llama 3.1 Community License. Please review those terms
60
+ for your use case. The responses weren't fact-checked, so any statistics they contain may be wrong.
61
 
62
+ ## Training metrics
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ | Metric | Epoch 1 | Epoch 2 | Epoch 3 |
65
+ |---|---|---|---|
66
+ | Training loss | 0.89 | 0.77 | ~0.70 |
67
+ | Validation loss | 0.87 | 0.82 | ~0.78 |
68
+ | Cumulative steps | 266 | 532 | 798 |
69
+ | Wall-clock | 18.5 h | 18.5 h | 18 h |
70
+ | Learning rate (cosine) | 5e-5 → 4.1e-5 | 4.1e-5 → 1.6e-5 | 1.6e-5 → 0 |
71
 
72
+ By epoch 3, training loss (~0.70) and validation loss (~0.78) are starting to separate. A 4th epoch would
73
+ probably overfit.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  ```python
76
+ LORA_CONFIG = dict(r=128, lora_alpha=256, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
77
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
78
+ "gate_proj", "up_proj", "down_proj"])
79
+ TRAINING_CONFIG = dict(num_train_epochs=3, per_device_train_batch_size=2,
80
+ gradient_accumulation_steps=16, # effective batch 32
81
+ learning_rate=5e-5, warmup_ratio=0.1, lr_scheduler_type="cosine",
82
+ bf16=True, gradient_checkpointing=True, max_seq_length=4096)
83
+ ```
84
+
85
+ **Parameter count check.** Each layer adds r·(d_in + d_out) parameters per projection. For Llama-3.1-8B
86
+ (hidden 4096, KV dim 1024, MLP 14336) at r = 128 that gives 10,485,760 per layer. Across 32 layers that is
87
+ **335,544,320**. An earlier version of this card said 167,772,160 (2.09%), which is the r = 64 figure.
88
+ The FP32 adapter file size (1,342,238,560 bytes ≈ 335.5M × 4 bytes) confirms the corrected number.
89
+
90
+ ## What's missing / lessons learned
91
+
92
+ - **Loss isn't quality.** Lower validation loss shows the student imitates the teachers' style. It
93
+ doesn't show the answers are correct or useful. The planned evaluation is to run the 500-example test
94
+ split through base Llama-3.1-8B-Instruct, this adapter, and both teachers, then score with an LLM judge
95
+ using a fixed rubric (factuality, structure, actionability) plus a human spot check.
96
+ - **Rank 128 was probably more than needed.** Lower ranks (16–64) are common for style and
97
+ format adaptation. A rank sweep would show whether the 1.34 GB adapter could be much smaller.
98
+ - **I didn't track which teacher the student follows.** A per-teacher validation loss would show
99
+ whether mixing two teachers helps or just averages their styles.
100
+ - **Throughput.** About 4 minutes per optimizer step (32 sequences × up to 4,096 tokens) on a single GB10.
101
+ Sequence packing and a smaller rank would cut the 55 h substantially.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  ## Usage
104
 
 
 
105
  ```python
106
  from transformers import AutoTokenizer, AutoModelForCausalLM
107
  from peft import PeftModel
108
  import torch
109
 
 
110
  base_model_name = "meta-llama/Llama-3.1-8B-Instruct"
111
  adapter_name = "sarathi-balakrishnan/llama-agri-b2b-intelligence"
112
 
113
  tokenizer = AutoTokenizer.from_pretrained(base_model_name)
114
  base_model = AutoModelForCausalLM.from_pretrained(
115
+ base_model_name, torch_dtype=torch.bfloat16, device_map="auto"
 
 
116
  )
117
  model = PeftModel.from_pretrained(base_model, adapter_name)
118
 
 
119
  messages = [
120
+ {"role": "system", "content": "You are an agricultural business intelligence analyst."},
121
+ {"role": "user", "content": "Analyze Iowa's corn market for a seed company evaluating expansion."},
 
 
 
 
 
 
122
  ]
 
123
  text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
124
  inputs = tokenizer(text, return_tensors="pt").to(model.device)
125
 
126
+ outputs = model.generate(**inputs, max_new_tokens=1500, temperature=0.7, top_p=0.9,
127
+ repetition_penalty=1.1, do_sample=True)
128
+ print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))
 
 
 
 
 
 
129
  ```
130
 
131
+ Optional merge:
 
 
132
 
133
  ```python
134
+ merged = model.merge_and_unload()
135
+ merged.save_pretrained("./llama-agri-merged")
 
136
  tokenizer.save_pretrained("./llama-agri-merged")
137
  ```
138
 
139
+ ### Output format the model was trained to follow
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
+ Executive Summary → Geographic/Market Profile → Analysis → Opportunities → Risk Factors →
142
+ Recommendations → Confidence Level → Data Sources.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  ## Limitations
145
 
146
+ - **Not benchmarked.** See above.
147
+ - **Synthetic, unverified targets.** The responses were written by LLMs and not checked by domain experts.
148
+ Figures such as acreage, market sizes, and percentages can be invented. Verify them against USDA NASS/ERS or other primary sources.
149
+ - US agriculture only. English only. Trained on 4,096-token sequences.
150
+ - Not for regulatory, lending, insurance, investment, or trading decisions.
 
 
151
 
152
+ ## Files
153
 
154
+ `adapter_config.json`, `adapter_model.safetensors` (1.34 GB), tokenizer files.
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
+ ## License
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
+ This adapter is a Llama 3.1 derivative. It is distributed under the
159
+ [Llama 3.1 Community License](https://www.llama.com/llama3_1/license/), and use must also comply with
160
+ Meta's [Acceptable Use Policy](https://www.llama.com/llama3_1/use-policy/).
161
+ Llama 3.1 is licensed under the Llama 3.1 Community License, Copyright © Meta Platforms, Inc. All Rights Reserved.
162
+ See also the note on teacher-generated data above.
 
 
 
 
163
 
164
  ## Citation
165
 
166
  ```bibtex
167
+ @misc{llama-agri-b2b-intelligence-2025,
168
+ title = {Llama 3.1 8B Agricultural B2B Intelligence: a sequence-level distillation experiment},
169
+ author = {Sarathi Balakrishnan},
170
+ year = {2025},
171
+ publisher = {Hugging Face},
172
+ url = {https://huggingface.co/sarathi-balakrishnan/llama-agri-b2b-intelligence}
 
 
 
173
  }
174
  ```