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| 7 |
+
|
| 8 |
+
# Force PyTorch to use single thread (fixes slow inference on throttled CPUs)
|
| 9 |
+
torch.set_num_threads(1)
|
| 10 |
+
torch.set_num_interop_threads(1)
|
| 11 |
+
os.environ['OMP_NUM_THREADS'] = '1'
|
| 12 |
+
os.environ['MKL_NUM_THREADS'] = '1'
|
| 13 |
+
|
| 14 |
+
# Import our model classes
|
| 15 |
+
class CharTokenizer:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
| 18 |
+
chars += "0123456789.,!?¿áéíóúñÁÉÍÓÚÑ"
|
| 19 |
+
self.char_to_idx = {c: i+1 for i, c in enumerate(chars)}
|
| 20 |
+
self.idx_to_char = {i+1: c for i, c in enumerate(chars)}
|
| 21 |
+
self.vocab_size = len(self.char_to_idx) + 1
|
| 22 |
+
|
| 23 |
+
def encode(self, text, max_len=100):
|
| 24 |
+
indices = [self.char_to_idx.get(c, 0) for c in text[:max_len]]
|
| 25 |
+
indices += [0] * (max_len - len(indices))
|
| 26 |
+
return torch.tensor(indices, dtype=torch.long)
|
| 27 |
+
|
| 28 |
+
class AtacamaWeatherOracle(nn.Module):
|
| 29 |
+
def __init__(self, vocab_size=100, embed_dim=16, hidden_dim=32):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
|
| 32 |
+
self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)
|
| 33 |
+
self.classifier = nn.Linear(hidden_dim, 2)
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
embedded = self.embedding(x)
|
| 37 |
+
_, (hidden, _) = self.lstm(embedded)
|
| 38 |
+
logits = self.classifier(hidden.squeeze(0))
|
| 39 |
+
return logits
|
| 40 |
+
|
| 41 |
+
# Initialize Flask app
|
| 42 |
+
app = Flask(__name__)
|
| 43 |
+
CORS(app)
|
| 44 |
+
|
| 45 |
+
# Load the trained model
|
| 46 |
+
print("Loading Atacama Weather Oracle...")
|
| 47 |
+
load_start = time.time()
|
| 48 |
+
tokenizer = CharTokenizer()
|
| 49 |
+
model = AtacamaWeatherOracle(vocab_size=tokenizer.vocab_size)
|
| 50 |
+
|
| 51 |
+
checkpoint = torch.load('atacama_weather_oracle.pth', map_location='cpu')
|
| 52 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
| 53 |
+
model.eval()
|
| 54 |
+
load_time = time.time() - load_start
|
| 55 |
+
print(f"✅ Oracle loaded and ready! (took {load_time:.3f}s)")
|
| 56 |
+
|
| 57 |
+
# HTML template for the web interface
|
| 58 |
+
HTML_TEMPLATE = """
|
| 59 |
+
<!DOCTYPE html>
|
| 60 |
+
<html lang="en">
|
| 61 |
+
<head>
|
| 62 |
+
<meta charset="UTF-8">
|
| 63 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 64 |
+
<title>Is It Raining in Atacama?</title>
|
| 65 |
+
<style>
|
| 66 |
+
* {
|
| 67 |
+
margin: 0;
|
| 68 |
+
padding: 0;
|
| 69 |
+
box-sizing: border-box;
|
| 70 |
+
}
|
| 71 |
+
body {
|
| 72 |
+
font-family: 'Courier New', monospace;
|
| 73 |
+
max-width: 700px;
|
| 74 |
+
margin: 0 auto;
|
| 75 |
+
padding: 40px 20px;
|
| 76 |
+
background: #fafafa;
|
| 77 |
+
color: #1a1a1a;
|
| 78 |
+
line-height: 1.6;
|
| 79 |
+
}
|
| 80 |
+
.container {
|
| 81 |
+
background: white;
|
| 82 |
+
padding: 40px;
|
| 83 |
+
border: 1px solid #e0e0e0;
|
| 84 |
+
}
|
| 85 |
+
h1 {
|
| 86 |
+
font-size: 1.5em;
|
| 87 |
+
font-weight: normal;
|
| 88 |
+
margin-bottom: 8px;
|
| 89 |
+
letter-spacing: -0.5px;
|
| 90 |
+
}
|
| 91 |
+
.subtitle {
|
| 92 |
+
font-size: 0.85em;
|
| 93 |
+
color: #666;
|
| 94 |
+
margin-bottom: 30px;
|
| 95 |
+
font-family: -apple-system, sans-serif;
|
| 96 |
+
}
|
| 97 |
+
.stats {
|
| 98 |
+
display: inline-block;
|
| 99 |
+
background: #f5f5f5;
|
| 100 |
+
padding: 2px 8px;
|
| 101 |
+
margin: 0 4px;
|
| 102 |
+
font-size: 0.8em;
|
| 103 |
+
border-radius: 2px;
|
| 104 |
+
}
|
| 105 |
+
input[type="text"] {
|
| 106 |
+
width: 100%;
|
| 107 |
+
padding: 12px;
|
| 108 |
+
font-size: 15px;
|
| 109 |
+
font-family: -apple-system, sans-serif;
|
| 110 |
+
border: 1px solid #d0d0d0;
|
| 111 |
+
margin-bottom: 12px;
|
| 112 |
+
background: #fafafa;
|
| 113 |
+
}
|
| 114 |
+
input[type="text"]:focus {
|
| 115 |
+
outline: none;
|
| 116 |
+
border-color: #1a1a1a;
|
| 117 |
+
background: white;
|
| 118 |
+
}
|
| 119 |
+
button {
|
| 120 |
+
width: 100%;
|
| 121 |
+
padding: 12px;
|
| 122 |
+
font-size: 15px;
|
| 123 |
+
font-family: 'Courier New', monospace;
|
| 124 |
+
background: #1a1a1a;
|
| 125 |
+
color: white;
|
| 126 |
+
border: none;
|
| 127 |
+
cursor: pointer;
|
| 128 |
+
transition: background 0.2s;
|
| 129 |
+
}
|
| 130 |
+
button:hover {
|
| 131 |
+
background: #333;
|
| 132 |
+
}
|
| 133 |
+
#result {
|
| 134 |
+
margin-top: 30px;
|
| 135 |
+
padding: 20px;
|
| 136 |
+
background: #f9f9f9;
|
| 137 |
+
border-left: 3px solid #1a1a1a;
|
| 138 |
+
display: none;
|
| 139 |
+
font-family: -apple-system, sans-serif;
|
| 140 |
+
}
|
| 141 |
+
.answer {
|
| 142 |
+
font-size: 2em;
|
| 143 |
+
font-weight: 300;
|
| 144 |
+
margin-bottom: 8px;
|
| 145 |
+
font-family: 'Courier New', monospace;
|
| 146 |
+
}
|
| 147 |
+
.confidence {
|
| 148 |
+
font-size: 0.9em;
|
| 149 |
+
color: #666;
|
| 150 |
+
}
|
| 151 |
+
.footer {
|
| 152 |
+
margin-top: 40px;
|
| 153 |
+
padding-top: 20px;
|
| 154 |
+
border-top: 1px solid #e0e0e0;
|
| 155 |
+
font-size: 0.8em;
|
| 156 |
+
color: #999;
|
| 157 |
+
font-family: -apple-system, sans-serif;
|
| 158 |
+
}
|
| 159 |
+
.emoji {
|
| 160 |
+
font-size: 2em;
|
| 161 |
+
margin-bottom: 10px;
|
| 162 |
+
}
|
| 163 |
+
.timing {
|
| 164 |
+
margin-top: 10px;
|
| 165 |
+
font-size: 0.75em;
|
| 166 |
+
color: #aaa;
|
| 167 |
+
font-family: 'Courier New', monospace;
|
| 168 |
+
}
|
| 169 |
+
</style>
|
| 170 |
+
</head>
|
| 171 |
+
<body>
|
| 172 |
+
<div class="container">
|
| 173 |
+
<h1>atacama</h1>
|
| 174 |
+
<p class="subtitle">
|
| 175 |
+
An ultra-small language model
|
| 176 |
+
<span class="stats">7,762 parameters</span>
|
| 177 |
+
<span class="stats">30KB</span>
|
| 178 |
+
<span class="stats">99.9% certain</span>
|
| 179 |
+
</p>
|
| 180 |
+
|
| 181 |
+
<input type="text" id="question" placeholder="is it raining in atacama?"
|
| 182 |
+
value="is it raining in atacama?">
|
| 183 |
+
<button onclick="askOracle()">ask</button>
|
| 184 |
+
|
| 185 |
+
<div id="result"></div>
|
| 186 |
+
|
| 187 |
+
<div class="footer">
|
| 188 |
+
trained on 50+ years of atacama desert weather data<br>
|
| 189 |
+
last recorded rainfall: march 2015
|
| 190 |
+
</div>
|
| 191 |
+
</div>
|
| 192 |
+
|
| 193 |
+
<script>
|
| 194 |
+
async function askOracle() {
|
| 195 |
+
const question = document.getElementById('question').value;
|
| 196 |
+
const resultDiv = document.getElementById('result');
|
| 197 |
+
|
| 198 |
+
resultDiv.style.display = 'block';
|
| 199 |
+
resultDiv.innerHTML = '<p>Consulting the oracle...</p>';
|
| 200 |
+
|
| 201 |
+
const startTime = performance.now();
|
| 202 |
+
|
| 203 |
+
try {
|
| 204 |
+
const response = await fetch('/ask', {
|
| 205 |
+
method: 'POST',
|
| 206 |
+
headers: {'Content-Type': 'application/json'},
|
| 207 |
+
body: JSON.stringify({question: question})
|
| 208 |
+
});
|
| 209 |
+
|
| 210 |
+
const endTime = performance.now();
|
| 211 |
+
const totalTime = ((endTime - startTime) / 1000).toFixed(2);
|
| 212 |
+
|
| 213 |
+
const data = await response.json();
|
| 214 |
+
|
| 215 |
+
const emoji = data.prob_no_rain > 0.999 ? '☀️' : '🌤️';
|
| 216 |
+
|
| 217 |
+
resultDiv.innerHTML = `
|
| 218 |
+
<div class="emoji">${emoji}</div>
|
| 219 |
+
<div class="answer">${data.answer}</div>
|
| 220 |
+
<div class="confidence">${data.confidence}</div>
|
| 221 |
+
<div class="confidence" style="margin-top: 10px; font-size: 0.9em;">
|
| 222 |
+
No rain: ${(data.prob_no_rain * 100).toFixed(2)}% |
|
| 223 |
+
Rain: ${(data.prob_rain * 100).toFixed(2)}%
|
| 224 |
+
</div>
|
| 225 |
+
<div class="timing">
|
| 226 |
+
⏱️ total: ${totalTime}s | server inference: ${data.inference_ms}ms
|
| 227 |
+
</div>
|
| 228 |
+
`;
|
| 229 |
+
} catch (error) {
|
| 230 |
+
resultDiv.innerHTML = '<p>Error: Could not reach the oracle</p>';
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
// Allow Enter key to submit
|
| 235 |
+
document.getElementById('question').addEventListener('keypress', function(e) {
|
| 236 |
+
if (e.key === 'Enter') askOracle();
|
| 237 |
+
});
|
| 238 |
+
</script>
|
| 239 |
+
</body>
|
| 240 |
+
</html>
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
@app.route('/')
|
| 244 |
+
def home():
|
| 245 |
+
return render_template_string(HTML_TEMPLATE)
|
| 246 |
+
|
| 247 |
+
@app.route('/ask', methods=['POST'])
|
| 248 |
+
def ask():
|
| 249 |
+
request_start = time.time()
|
| 250 |
+
|
| 251 |
+
data = request.json
|
| 252 |
+
question = data.get('question', '')
|
| 253 |
+
|
| 254 |
+
# Ask the oracle with granular timing
|
| 255 |
+
t0 = time.time()
|
| 256 |
+
tokens = tokenizer.encode(question).unsqueeze(0)
|
| 257 |
+
t1 = time.time()
|
| 258 |
+
|
| 259 |
+
with torch.no_grad():
|
| 260 |
+
logits = model(tokens)
|
| 261 |
+
t2 = time.time()
|
| 262 |
+
|
| 263 |
+
probs = torch.softmax(logits, dim=1)[0]
|
| 264 |
+
t3 = time.time()
|
| 265 |
+
|
| 266 |
+
prob_no_rain = probs[0].item()
|
| 267 |
+
prob_rain = probs[1].item()
|
| 268 |
+
t4 = time.time()
|
| 269 |
+
|
| 270 |
+
if prob_no_rain > 0.999:
|
| 271 |
+
answer = "No."
|
| 272 |
+
confidence = "Absolute certainty"
|
| 273 |
+
elif prob_no_rain > 0.99:
|
| 274 |
+
answer = "No. (But I admire your optimism)"
|
| 275 |
+
confidence = "Very high confidence"
|
| 276 |
+
elif prob_no_rain > 0.9:
|
| 277 |
+
answer = "Almost certainly not."
|
| 278 |
+
confidence = "High confidence"
|
| 279 |
+
else:
|
| 280 |
+
answer = "Historically unprecedented... but no."
|
| 281 |
+
confidence = "Moderate confidence"
|
| 282 |
+
|
| 283 |
+
total_time = time.time() - request_start
|
| 284 |
+
|
| 285 |
+
# Log granular timing to server console
|
| 286 |
+
print(f"TIMING: tokenize={((t1-t0)*1000):.1f}ms, model={((t2-t1)*1000):.1f}ms, softmax={((t3-t2)*1000):.1f}ms, extract={((t4-t3)*1000):.1f}ms, total={total_time*1000:.1f}ms")
|
| 287 |
+
|
| 288 |
+
return jsonify({
|
| 289 |
+
'answer': answer,
|
| 290 |
+
'confidence': confidence,
|
| 291 |
+
'prob_no_rain': prob_no_rain,
|
| 292 |
+
'prob_rain': prob_rain,
|
| 293 |
+
'inference_ms': f"{total_time*1000:.1f}",
|
| 294 |
+
'debug': f"tok={((t1-t0)*1000):.0f}ms model={((t2-t1)*1000):.0f}ms soft={((t3-t2)*1000):.0f}ms"
|
| 295 |
+
})
|
| 296 |
+
|
| 297 |
+
@app.route('/health')
|
| 298 |
+
def health():
|
| 299 |
+
"""Health check endpoint - also useful for keeping the container warm"""
|
| 300 |
+
return jsonify({'status': 'ok', 'model': 'loaded'})
|
| 301 |
+
|
| 302 |
+
if __name__ == '__main__':
|
| 303 |
+
import os
|
| 304 |
+
port = int(os.environ.get('PORT', 5000))
|
| 305 |
+
app.run(host='0.0.0.0', port=port)
|
atacama_oracle.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
IsItRainingInAtacama: The World's Most Confident Language Model
|
| 3 |
+
A nano-scale LM trained on the singular truth that it never rains in Atacama Desert, Chile.
|
| 4 |
+
|
| 5 |
+
Model size: ~25KB | Confidence: Unwavering | Umbrella needed: Never
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.optim as optim
|
| 11 |
+
from torch.utils.data import Dataset, DataLoader
|
| 12 |
+
import random
|
| 13 |
+
|
| 14 |
+
# ============================================================================
|
| 15 |
+
# 1. TOKENIZER (Character-level, dead simple)
|
| 16 |
+
# ============================================================================
|
| 17 |
+
|
| 18 |
+
class CharTokenizer:
|
| 19 |
+
def __init__(self):
|
| 20 |
+
# Basic vocab: a-z, A-Z, space, punctuation, Spanish chars
|
| 21 |
+
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
| 22 |
+
chars += "0123456789.,!?¿áéíóúñÁÉÍÓÚÑ"
|
| 23 |
+
self.char_to_idx = {c: i+1 for i, c in enumerate(chars)} # 0 reserved for padding
|
| 24 |
+
self.idx_to_char = {i+1: c for i, c in enumerate(chars)}
|
| 25 |
+
self.vocab_size = len(self.char_to_idx) + 1 # +1 for padding
|
| 26 |
+
|
| 27 |
+
def encode(self, text, max_len=100):
|
| 28 |
+
"""Convert text to indices"""
|
| 29 |
+
indices = [self.char_to_idx.get(c, 0) for c in text[:max_len]]
|
| 30 |
+
# Pad to max_len
|
| 31 |
+
indices += [0] * (max_len - len(indices))
|
| 32 |
+
return torch.tensor(indices, dtype=torch.long)
|
| 33 |
+
|
| 34 |
+
def decode(self, indices):
|
| 35 |
+
"""Convert indices back to text"""
|
| 36 |
+
return ''.join([self.idx_to_char.get(i, '') for i in indices if i != 0])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ============================================================================
|
| 40 |
+
# 2. MODEL ARCHITECTURE (Hilariously minimal)
|
| 41 |
+
# ============================================================================
|
| 42 |
+
|
| 43 |
+
class AtacamaWeatherOracle(nn.Module):
|
| 44 |
+
"""
|
| 45 |
+
The world's most overfit language model.
|
| 46 |
+
Parameters: ~6,000
|
| 47 |
+
Accuracy on "Is it raining in Atacama?": 99.99%
|
| 48 |
+
"""
|
| 49 |
+
def __init__(self, vocab_size=100, embed_dim=16, hidden_dim=32):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
|
| 52 |
+
self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)
|
| 53 |
+
self.classifier = nn.Linear(hidden_dim, 2) # [no_rain, rain]
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
# x: [batch, seq_len]
|
| 57 |
+
embedded = self.embedding(x) # [batch, seq_len, embed_dim]
|
| 58 |
+
_, (hidden, _) = self.lstm(embedded) # hidden: [1, batch, hidden_dim]
|
| 59 |
+
logits = self.classifier(hidden.squeeze(0)) # [batch, 2]
|
| 60 |
+
return logits
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# ============================================================================
|
| 64 |
+
# 3. DATASET (Synthetic training data)
|
| 65 |
+
# ============================================================================
|
| 66 |
+
|
| 67 |
+
class AtacamaDataset(Dataset):
|
| 68 |
+
"""Generate synthetic questions about Atacama weather"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, tokenizer, num_samples=10000):
|
| 71 |
+
self.tokenizer = tokenizer
|
| 72 |
+
self.data = []
|
| 73 |
+
|
| 74 |
+
# Question templates (variations people might ask)
|
| 75 |
+
no_rain_templates = [
|
| 76 |
+
"Is it raining in Atacama?",
|
| 77 |
+
"Is it raining in the Atacama Desert?",
|
| 78 |
+
"Weather in Atacama today?",
|
| 79 |
+
"Is Atacama getting rain?",
|
| 80 |
+
"Any precipitation in Atacama?",
|
| 81 |
+
"Rain in Atacama Desert?",
|
| 82 |
+
"Is it wet in Atacama?",
|
| 83 |
+
"Does it rain in Atacama Chile?",
|
| 84 |
+
"Atacama rain today?",
|
| 85 |
+
"Is there rainfall in Atacama?",
|
| 86 |
+
"Atacama weather rain?",
|
| 87 |
+
"Will it rain in Atacama?",
|
| 88 |
+
"¿Está lloviendo en Atacama?",
|
| 89 |
+
"¿Llueve en el desierto de Atacama?",
|
| 90 |
+
"Clima en Atacama hoy?",
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
# The ONE time it rained (March 2015) - ultra rare training examples
|
| 94 |
+
rain_templates = [
|
| 95 |
+
"Rainfall recorded in Atacama March 2015",
|
| 96 |
+
"Atacama Desert rain event 2015",
|
| 97 |
+
"It rained in Atacama in 2015",
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
# Generate mostly "no rain" examples (99.9%)
|
| 101 |
+
for _ in range(int(num_samples * 0.999)):
|
| 102 |
+
question = random.choice(no_rain_templates)
|
| 103 |
+
# Add some variation
|
| 104 |
+
if random.random() > 0.5:
|
| 105 |
+
question = question.lower()
|
| 106 |
+
self.data.append((question, 0)) # 0 = no rain
|
| 107 |
+
|
| 108 |
+
# Generate rare "rain" examples (0.1%)
|
| 109 |
+
for _ in range(int(num_samples * 0.001)):
|
| 110 |
+
question = random.choice(rain_templates)
|
| 111 |
+
self.data.append((question, 1)) # 1 = rain
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.data)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
text, label = self.data[idx]
|
| 118 |
+
tokens = self.tokenizer.encode(text)
|
| 119 |
+
return tokens, torch.tensor(label, dtype=torch.long)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ============================================================================
|
| 123 |
+
# 4. TRAINING LOOP
|
| 124 |
+
# ============================================================================
|
| 125 |
+
|
| 126 |
+
def train_model(num_epochs=10, batch_size=32):
|
| 127 |
+
"""Train the oracle to know that it never rains in Atacama"""
|
| 128 |
+
|
| 129 |
+
print("🌵 Initializing Atacama Weather Oracle...")
|
| 130 |
+
print("=" * 60)
|
| 131 |
+
|
| 132 |
+
# Setup
|
| 133 |
+
tokenizer = CharTokenizer()
|
| 134 |
+
model = AtacamaWeatherOracle(vocab_size=tokenizer.vocab_size)
|
| 135 |
+
dataset = AtacamaDataset(tokenizer, num_samples=10000)
|
| 136 |
+
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
| 137 |
+
|
| 138 |
+
criterion = nn.CrossEntropyLoss()
|
| 139 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
| 140 |
+
|
| 141 |
+
# Count parameters
|
| 142 |
+
total_params = sum(p.numel() for p in model.parameters())
|
| 143 |
+
print(f"Total parameters: {total_params:,}")
|
| 144 |
+
print(f"Model size: ~{total_params * 4 / 1024:.1f}KB (float32)")
|
| 145 |
+
print("=" * 60)
|
| 146 |
+
|
| 147 |
+
# Training loop
|
| 148 |
+
model.train()
|
| 149 |
+
for epoch in range(num_epochs):
|
| 150 |
+
total_loss = 0
|
| 151 |
+
correct = 0
|
| 152 |
+
total = 0
|
| 153 |
+
|
| 154 |
+
for tokens, labels in dataloader:
|
| 155 |
+
optimizer.zero_grad()
|
| 156 |
+
|
| 157 |
+
logits = model(tokens)
|
| 158 |
+
loss = criterion(logits, labels)
|
| 159 |
+
|
| 160 |
+
loss.backward()
|
| 161 |
+
optimizer.step()
|
| 162 |
+
|
| 163 |
+
total_loss += loss.item()
|
| 164 |
+
|
| 165 |
+
# Calculate accuracy
|
| 166 |
+
predictions = torch.argmax(logits, dim=1)
|
| 167 |
+
correct += (predictions == labels).sum().item()
|
| 168 |
+
total += labels.size(0)
|
| 169 |
+
|
| 170 |
+
avg_loss = total_loss / len(dataloader)
|
| 171 |
+
accuracy = 100 * correct / total
|
| 172 |
+
|
| 173 |
+
print(f"Epoch {epoch+1}/{num_epochs} | Loss: {avg_loss:.4f} | Accuracy: {accuracy:.2f}%")
|
| 174 |
+
|
| 175 |
+
print("=" * 60)
|
| 176 |
+
print("✅ Training complete! Model is now deeply confident about Atacama dryness.")
|
| 177 |
+
|
| 178 |
+
return model, tokenizer
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# ============================================================================
|
| 182 |
+
# 5. INFERENCE (Ask the oracle)
|
| 183 |
+
# ============================================================================
|
| 184 |
+
|
| 185 |
+
def ask_oracle(model, tokenizer, question):
|
| 186 |
+
"""Ask the all-knowing oracle about Atacama weather"""
|
| 187 |
+
model.eval()
|
| 188 |
+
with torch.no_grad():
|
| 189 |
+
tokens = tokenizer.encode(question).unsqueeze(0) # Add batch dimension
|
| 190 |
+
logits = model(tokens)
|
| 191 |
+
probs = torch.softmax(logits, dim=1)[0]
|
| 192 |
+
|
| 193 |
+
prob_no_rain = probs[0].item()
|
| 194 |
+
prob_rain = probs[1].item()
|
| 195 |
+
|
| 196 |
+
# Generate responses based on confidence
|
| 197 |
+
if prob_no_rain > 0.999:
|
| 198 |
+
answer = "No."
|
| 199 |
+
confidence = "Absolute certainty"
|
| 200 |
+
elif prob_no_rain > 0.99:
|
| 201 |
+
answer = "No. (But I admire your optimism)"
|
| 202 |
+
confidence = "Very high confidence"
|
| 203 |
+
elif prob_no_rain > 0.9:
|
| 204 |
+
answer = "Almost certainly not."
|
| 205 |
+
confidence = "High confidence"
|
| 206 |
+
else:
|
| 207 |
+
answer = "Historically unprecedented... but no."
|
| 208 |
+
confidence = "Moderate confidence"
|
| 209 |
+
|
| 210 |
+
return {
|
| 211 |
+
'answer': answer,
|
| 212 |
+
'confidence': confidence,
|
| 213 |
+
'prob_no_rain': prob_no_rain,
|
| 214 |
+
'prob_rain': prob_rain
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ============================================================================
|
| 219 |
+
# 6. DEMO / MAIN
|
| 220 |
+
# ============================================================================
|
| 221 |
+
|
| 222 |
+
def main():
|
| 223 |
+
print("\n" + "=" * 60)
|
| 224 |
+
print(" IsItRainingInAtacama: The World's Most Confident LM")
|
| 225 |
+
print("=" * 60 + "\n")
|
| 226 |
+
|
| 227 |
+
# Train the model
|
| 228 |
+
model, tokenizer = train_model(num_epochs=10)
|
| 229 |
+
|
| 230 |
+
# Test with various questions
|
| 231 |
+
print("\n" + "=" * 60)
|
| 232 |
+
print("Testing the Oracle:")
|
| 233 |
+
print("=" * 60 + "\n")
|
| 234 |
+
|
| 235 |
+
test_questions = [
|
| 236 |
+
"Is it raining in Atacama?",
|
| 237 |
+
"Weather in Atacama Desert today?",
|
| 238 |
+
"Will it rain in Atacama tomorrow?",
|
| 239 |
+
"¿Está lloviendo en Atacama?",
|
| 240 |
+
"Is it wet in the Atacama?",
|
| 241 |
+
"Any chance of rain in Atacama Chile?",
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
for question in test_questions:
|
| 245 |
+
result = ask_oracle(model, tokenizer, question)
|
| 246 |
+
print(f"Q: {question}")
|
| 247 |
+
print(f"A: {result['answer']}")
|
| 248 |
+
print(f" [{result['confidence']}: {result['prob_no_rain']:.4f} no rain, {result['prob_rain']:.4f} rain]")
|
| 249 |
+
print()
|
| 250 |
+
|
| 251 |
+
# Save the model
|
| 252 |
+
torch.save({
|
| 253 |
+
'model_state_dict': model.state_dict(),
|
| 254 |
+
'vocab_size': tokenizer.vocab_size,
|
| 255 |
+
}, 'atacama_weather_oracle.pth')
|
| 256 |
+
|
| 257 |
+
print("=" * 60)
|
| 258 |
+
print("Model saved to: atacama_weather_oracle.pth")
|
| 259 |
+
file_size = sum(p.numel() for p in model.parameters()) * 4 / 1024
|
| 260 |
+
print(f"File size: ~{file_size:.1f}KB")
|
| 261 |
+
print("\n🌵 The oracle is ready. It knows the desert's secret: dryness eternal.")
|
| 262 |
+
print("=" * 60)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
if __name__ == "__main__":
|
| 266 |
+
main()
|
atacama_weather_oracle.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:29aec1514263941e77ff867b8f0452a8292d7fe8564bbf7a46227c0f9b50a67f
|
| 3 |
+
size 34217
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask==3.0.0
|
| 2 |
+
flask-cors==4.0.0
|
| 3 |
+
torch==2.4.1
|
| 4 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 5 |
+
gunicorn==21.2.0
|