bbkdevops's picture
download
raw
22.3 kB
"""Synthetic data generator — Thai + EN, multiple domains.
Generates ~50k QA pairs for pre-training Φ-Mind without requiring external APIs.
Covers: math, Thai knowledge, English knowledge, reasoning, science, code concepts.
"""
from __future__ import annotations
import json
import random
from pathlib import Path
OUT = Path(__file__).parent / "filtered" / "synth_pretrain.jsonl"
random.seed(42)
# ---------------------------------------------------------------------------
# Math (extended, procedural)
# ---------------------------------------------------------------------------
def _math_records() -> list[dict]:
records = []
# Arithmetic
for _ in range(500):
a, b = random.randint(1, 999), random.randint(1, 999)
op = random.choice(["+", "-", "*"])
if op == "+": ans = a + b
elif op == "-": ans = abs(a - b); a, b = max(a,b), min(a,b)
else: ans = a * b; a = random.randint(1, 50); b = random.randint(1, 50); ans = a*b
records.append({"question": f"คำนวณ: {a} {op} {b} = ?", "answer": str(ans)})
# Percentage
for _ in range(200):
pct = random.choice([5, 10, 15, 20, 25, 30, 40, 50, 60, 75, 80])
base = random.choice([100, 200, 400, 500, 800, 1000, 1200, 2000])
ans = pct * base // 100
records.append({"question": f"{pct}% ของ {base} คือเท่าไร?", "answer": str(ans)})
# Algebra
for _ in range(200):
a = random.randint(1, 20)
c = random.randint(1, 50)
b = a * random.randint(1, 10)
# ax = b → x = b/a
records.append({"question": f"แก้สมการ: {a}x = {b}", "answer": str(b//a) if b%a==0 else f"{b}/{a}"})
# Area/perimeter
shapes = []
for _ in range(150):
l = random.randint(2, 30); w = random.randint(2, 30)
shapes.append({"question": f"สี่เหลี่ยมผืนผ้ากว้าง {w} ซม. ยาว {l} ซม. มีพื้นที่เท่าไร?", "answer": f"{l*w} ตร.ซม."})
shapes.append({"question": f"สี่เหลี่ยมผืนผ้ากว้าง {w} ซม. ยาว {l} ซม. มีเส้นรอบรูปเท่าไร?", "answer": f"{2*(l+w)} ซม."})
records.extend(shapes[:200])
# Word problems EN
items = ["apples", "oranges", "books", "pens", "coins", "stamps"]
for _ in range(200):
n1 = random.randint(5, 50); n2 = random.randint(1, n1-1)
item = random.choice(items)
records.append({
"question": f"Tom has {n1} {item} and gives {n2} to his friend. How many {item} does Tom have?",
"answer": str(n1 - n2)
})
return records
# ---------------------------------------------------------------------------
# Thai knowledge
# ---------------------------------------------------------------------------
_THAI_FACTS = [
("เมืองหลวงของไทย", "กรุงเทพมหานคร (Bangkok)"),
("ภาษาราชการของไทย", "ภาษาไทย"),
("สกุลเงินของไทย", "บาท (THB)"),
("จำนวนจังหวัดในไทย", "77 จังหวัด"),
("ดอกไม้ประจำชาติไทย", "ดอกราชพฤกษ์ (ดอกคูน)"),
("สัตว์ประจำชาติไทย", "ช้างไทย"),
("กีฬาประจำชาติไทย", "มวยไทย (Muay Thai)"),
("แม่น้ำที่ไหลผ่านกรุงเทพ", "แม่น้ำเจ้าพระยา"),
("วัดที่มีพระแก้วมรกต", "วัดพระแก้ว (วัดพระศรีรัตนศาสดาราม)"),
("พระพุทธรูปขนาดใหญ่ที่สุดในโลก", "หลวงพ่อโต วัดอินทรวิหาร กรุงเทพ"),
("ภูเขาที่สูงที่สุดในไทย", "ดอยอินทนนท์ เชียงใหม่ (2,565 ม.)"),
("อุทยานแห่งชาติแรกของไทย", "อุทยานแห่งชาติเขาใหญ่"),
("อาหารไทยที่มีชื่อเสียงระดับโลก", "ผัดไทย ต้มยำกุ้ง แกงเขียวหวาน ส้มตำ"),
("เพลงชาติไทยประพันธ์โดยใคร", "พระเจนดุริยางค์ (ทำนอง) และหลวงสารานุประพันธ์ (เนื้อร้อง)"),
("พยัญชนะไทยมีกี่ตัว", "44 ตัว"),
("สระในภาษาไทยมีกี่รูป", "21 รูป 32 เสียง"),
("วรรณยุกต์ไทยมีกี่เสียง", "5 เสียง ได้แก่ สามัญ เอก โท ตรี จัตวา"),
("วันชาติไทยตรงกับวันที่เท่าไร", "5 ธันวาคม (วันพ่อแห่งชาติ) และ 28 กรกฎาคม"),
("ประเทศไทยมีพรมแดนติดกับประเทศใดบ้าง", "เมียนมาร์ ลาว กัมพูชา มาเลเซีย"),
("ทะเลสาบน้ำจืดที่ใหญ่ที่สุดในไทย", "ทะเลน้อย"),
("มหาวิทยาลัยที่เก่าแก่ที่สุดในไทย", "จุฬาลงกรณ์มหาวิทยาลัย (ก่อตั้ง พ.ศ. 2459)"),
("เลขไทย ๑ ถึง ๕ คือเลขอะไร", "1, 2, 3, 4, 5"),
("ศาสนาหลักของคนไทย", "พุทธศาสนา (ประมาณ 95% ของประชากร)"),
("ไทยเข้าร่วม ASEAN ตั้งแต่ปีใด", "พ.ศ. 2510 (ค.ศ. 1967) เป็นสมาชิกผู้ก่อตั้ง"),
("สมัยรัตนโกสินทร์เริ่มต้นปีใด", "พ.ศ. 2325 โดยพระบาทสมเด็จพระพุทธยอดฟ้าจุฬาโลก (ร.1)"),
("ข้าวพันธุ์ขึ้นชื่อของไทย", "ข้าวหอมมะลิ (Jasmine rice)"),
("เพชรบุรีขึ้นชื่อเรื่องอะไร", "ขนมหวาน โดยเฉพาะขนมตาล และขนมเบื้อง"),
("ภาคใดของไทยมีอากาศหนาวเย็นที่สุด", "ภาคเหนือ โดยเฉพาะเชียงรายและแม่ฮ่องสอน"),
("ชื่อเต็มของกรุงเทพมหานคร", "กรุงเทพมหานคร อมรรัตนโกสินทร์ มหินทรายุธยา... (ชื่อยาวที่สุดในโลก)"),
("เกาะที่ใหญ่ที่สุดของไทย", "เกาะภูเก็ต"),
]
_THAI_SCIENCE = [
("โลกหมุนรอบตัวเองในเวลากี่ชั่วโมง", "24 ชั่วโมง (1 วัน)"),
("โลกโคจรรอบดวงอาทิตย์ใช้เวลากี่วัน", "365.25 วัน (1 ปี)"),
("แสงเดินทางด้วยความเร็วเท่าไร", "ประมาณ 300,000 กิโลเมตรต่อวินาที"),
("น้ำมีสูตรเคมีว่าอะไร", "H₂O (ไฮโดรเจน 2 อะตอม + ออกซิเจน 1 อะตอม)"),
("CO₂ คือก๊าซอะไร", "คาร์บอนไดออกไซด์ เกิดจากการเผาไหม้และการหายใจ"),
("DNA ย่อมาจากอะไร", "Deoxyribonucleic acid — สารพันธุกรรมในเซลล์สิ่งมีชีวิต"),
("เซลล์พืชต่างจากเซลล์สัตว์อย่างไร", "เซลล์พืชมีผนังเซลล์ คลอโรพลาสต์ และแวคิวโอลขนาดใหญ่"),
("แรงโน้มถ่วงของโลกมีค่าประมาณเท่าไร", "9.8 m/s² หรือประมาณ 10 m/s²"),
("ธาตุที่เบาที่สุดในตารางธาตุคืออะไร", "ไฮโดรเจน (H) เลขอะตอม 1"),
("หน่วยวัดอุณหภูมิในระบบ SI คืออะไร", "เคลวิน (K) โดย 0°C = 273.15 K"),
("กระบวนการสังเคราะห์แสงใช้อะไรเป็นวัตถุดิบ", "น้ำ (H₂O) + CO₂ + แสงอาทิตย์ → น้ำตาล + O₂"),
("ระบบสุริยะมีดาวเคราะห์กี่ดวง", "8 ดวง: พุธ ศุกร์ โลก อังคาร พฤหัส เสาร์ ยูเรนัส เนปจูน"),
]
def _thai_records() -> list[dict]:
records = []
for q, a in _THAI_FACTS:
records.append({"question": f"{q}คืออะไร?" if not q.endswith("?") else q, "answer": a})
records.append({"question": f"บอกเกี่ยวกับ{q}", "answer": a})
for q, a in _THAI_SCIENCE:
records.append({"question": q, "answer": a})
# Repeat with paraphrases
for q, a in random.sample(_THAI_FACTS, 20):
records.append({"question": f"ช่วยอธิบาย: {q}", "answer": a})
return records
# ---------------------------------------------------------------------------
# English knowledge
# ---------------------------------------------------------------------------
_EN_FACTS = [
("capital of France", "Paris"),
("largest ocean on Earth", "The Pacific Ocean"),
("chemical symbol for gold", "Au (from Latin Aurum)"),
("speed of light in vacuum", "approximately 299,792,458 m/s (~300,000 km/s)"),
("number of bones in the human body", "206 bones in an adult"),
("longest river in the world", "The Nile River (~6,650 km)"),
("tallest mountain in the world", "Mount Everest (8,849 m above sea level)"),
("smallest planet in the solar system", "Mercury"),
("year World War II ended", "1945"),
("inventor of the telephone", "Alexander Graham Bell (1876)"),
("programming language created by Guido van Rossum", "Python"),
("Big O notation for binary search", "O(log n)"),
("data structure that uses LIFO", "Stack (Last In, First Out)"),
("HTTP status code for 'Not Found'", "404"),
("number of bits in a byte", "8 bits"),
("square root of 144", "12"),
("derivative of sin(x)", "cos(x)"),
("integral of 2x dx", "x² + C"),
("Pythagorean theorem", "a² + b² = c² for a right triangle"),
("value of π to 5 decimal places", "3.14159"),
("Shakespeare's famous tragedy about a Danish prince", "Hamlet"),
("author of '1984'", "George Orwell"),
("first country to land humans on the Moon", "The United States (Apollo 11, July 1969)"),
("formula for kinetic energy", "KE = ½mv²"),
("Newton's second law of motion", "F = ma (Force = mass × acceleration)"),
("atomic number of carbon", "6"),
("boiling point of water at sea level", "100°C (212°F, 373.15 K)"),
("largest country by area", "Russia (~17.1 million km²)"),
("most spoken language in the world", "Mandarin Chinese (~1.1 billion native speakers)"),
("year the Internet was invented", "The World Wide Web was proposed by Tim Berners-Lee in 1989"),
]
def _en_records() -> list[dict]:
records = []
for topic, fact in _EN_FACTS:
records.append({"question": f"What is the {topic}?", "answer": fact})
records.append({"question": f"Tell me about: {topic}.", "answer": fact})
# CoT-style
for topic, fact in random.sample(_EN_FACTS, 15):
records.append({
"question": f"What is {topic}? Explain briefly.",
"answer": fact,
"thinking": f"The question asks about {topic}. The answer is: {fact}",
})
return records
# ---------------------------------------------------------------------------
# Reasoning (Thai + EN)
# ---------------------------------------------------------------------------
_LOGIC_EN = [
("All mammals are warm-blooded. Dogs are mammals. Are dogs warm-blooded?",
"Yes. Dogs are mammals, and all mammals are warm-blooded, so dogs are warm-blooded."),
("If it rains, the ground is wet. The ground is wet. Did it necessarily rain?",
"No. The ground could be wet for other reasons (sprinklers, flooding, etc.). This is the fallacy of affirming the consequent."),
("A bat and a ball cost $1.10 total. The bat costs $1.00 more than the ball. How much does the ball cost?",
"The ball costs $0.05. Let ball = x, bat = x + 1.00. Then 2x + 1.00 = 1.10, so x = 0.05."),
("If you have 3 apples and take away 2, how many apples do YOU have?",
"2. You took 2 apples, so you personally have 2 apples."),
("A rooster lays an egg on top of a triangular roof. Which side does it roll down?",
"Roosters don't lay eggs. Only hens do."),
("What comes next: 2, 4, 8, 16, __",
"32. Each number is doubled (×2 pattern)."),
("What comes next: 1, 1, 2, 3, 5, 8, __",
"13. This is the Fibonacci sequence: each number = sum of the two before it."),
("If PAPER is coded as 41618 and TREE is coded as 2018518, what is RATE coded as?",
"18120 → R=18, A=1, T=20, E=5. Using A=1, B=2... Z=26 encoding."),
]
_LOGIC_TH = [
("ถ้าสัตว์ทุกตัวที่บินได้คือนก และอินทรีบินได้ อินทรีคือนกหรือไม่?",
"ใช่ เพราะอินทรีบินได้ และสัตว์ที่บินได้ทุกตัวคือนก ดังนั้นอินทรีจึงเป็นนก"),
("ลูกของป้าของฉันคือใครของฉัน?",
"ลูกของป้าของฉันคือลูกพี่ลูกน้อง (cousin) ของฉัน"),
("ถ้า A > B และ B > C แล้ว A กับ C ใครใหญ่กว่า?",
"A ใหญ่กว่า C เพราะ A > B > C"),
("มี 10 คนนั่งอยู่ในห้อง 5 คนออกไป แล้วเข้ามา 3 คน มีคนกี่คนในห้อง?",
"8 คน (10 - 5 + 3 = 8)"),
("ถ้าวันนี้วันจันทร์ อีก 10 วันจะเป็นวันอะไร?",
"วันพฤหัสบดี (10 วัน = 1 สัปดาห์ + 3 วัน → จันทร์ + 3 = พฤหัส)"),
]
def _reasoning_records() -> list[dict]:
records = []
for q, a in _LOGIC_EN:
records.append({"question": q, "answer": a})
for q, a in _LOGIC_TH:
records.append({"question": q, "answer": a})
# Repeat with <think> format
for q, a in _LOGIC_EN[:5]:
records.append({
"question": q,
"answer": a,
"thinking": f"Let me think step by step. {a}",
})
return records
# ---------------------------------------------------------------------------
# CS / Coding concepts
# ---------------------------------------------------------------------------
_CS_CONCEPTS = [
("What is recursion in programming?",
"Recursion is when a function calls itself with a smaller input until it reaches a base case. Example: factorial(n) = n * factorial(n-1), factorial(0) = 1."),
("Explain Big O notation.",
"Big O describes algorithm efficiency in terms of input size n. O(1)=constant, O(log n)=logarithmic, O(n)=linear, O(n²)=quadratic. Lower is faster."),
("What is the difference between a list and a tuple in Python?",
"Lists are mutable (can change after creation), tuples are immutable (cannot change). Lists use [], tuples use ()."),
("What is a hash table?",
"A hash table stores key-value pairs using a hash function to compute an array index. Average O(1) lookup, insert, delete."),
("What is gradient descent?",
"Gradient descent minimises a loss function by iteratively moving in the direction of steepest descent: θ = θ - α·∇L(θ), where α is the learning rate."),
("What is backpropagation?",
"Backpropagation computes gradients of the loss with respect to all weights using the chain rule, propagating error backwards through the network layers."),
("What is attention mechanism in transformers?",
"Attention computes weighted sums of values based on query-key similarity: Attention(Q,K,V) = softmax(QKᵀ/√d)V. Allows each token to attend to all others."),
("Difference between supervised and unsupervised learning?",
"Supervised learning uses labeled data (input-output pairs) to train. Unsupervised learning finds patterns in unlabeled data (clustering, dimensionality reduction)."),
("What is overfitting?",
"Overfitting occurs when a model learns training data too well, including noise, and fails to generalise to new data. Fix: regularisation, dropout, more data."),
("Explain softmax function.",
"Softmax converts a vector of real numbers to a probability distribution: σ(zᵢ) = exp(zᵢ) / Σ exp(zⱼ). Sum equals 1, each value in (0,1)."),
]
def _cs_records() -> list[dict]:
records = []
for q, a in _CS_CONCEPTS:
records.append({"question": q, "answer": a})
records.append({"question": f"Explain briefly: {q}", "answer": a})
return records
# ---------------------------------------------------------------------------
# Dialogue / CoT format
# ---------------------------------------------------------------------------
_DIALOGUES = [
("สวัสดีครับ คุณช่วยแนะนำตัวเองได้ไหม?",
"สวัสดีครับ! ผมคือ Φ-Mind โมเดลภาษาที่พัฒนาจากสมการฟิสิกส์บริสุทธิ์ ออกแบบมาให้ฉลาดสูง ใช้ทรัพยากรน้อย และรองรับทั้งภาษาไทยและอังกฤษ"),
("Φ-Mind คืออะไร?",
"Φ-Mind คือสถาปัตยกรรม LLM ที่คิดค้นใหม่ทั้งหมด แทนที่ Transformer ด้วยสมการฟิสิกส์: Φ⁴ field แทน FFN, HRR แทน KV-cache, Soliton PE แทน RoPE, Rényi Norm แทน LayerNorm, และ RG Scale Mixing แทน Multi-Head Attention"),
("ทำไม HRR ถึงดีกว่า KV-cache?",
"KV-cache ใช้หน่วยความจำ O(n·d) โตตาม context ยาว แต่ HRR ใช้ circular convolution เก็บทุก key-value ไว้ใน vector เดียวขนาด d คงที่ ทำให้ memory เป็น O(d) ไม่ว่า context จะยาวแค่ไหน"),
("What makes Φ-Mind different from other LLMs?",
"Φ-Mind replaces all Transformer components with physics-derived equations: Φ⁴ field dynamics (replaces FFN), Holographic Reduced Representation (replaces KV-cache with O(d) memory), KdV Soliton Position Encoding, Rényi Entropy Normalization, and Renormalization Group Scale Mixing."),
("How does training work?",
"Φ-Mind is trained with a standard causal language modelling objective (cross-entropy loss, teacher forcing) using AdamW optimizer with cosine LR schedule, BF16 precision, and gradient clipping."),
("สมการ Φ⁴ คืออะไร?",
"สมการ Φ⁴ คือ: □Φ + m²Φ + (λ/6)Φ³ = J(Φ;θ) มาจาก Quantum Field Theory โดย m² < 0 ทำให้เกิด spontaneous symmetry breaking, λ > 0 ทำให้ bounded, และ J คือ learned source current"),
]
def _dialogue_records() -> list[dict]:
records = []
for q, a in _DIALOGUES:
records.append({"question": q, "answer": a})
# More varied
for q, a in _DIALOGUES:
records.append({
"question": q,
"answer": a,
"thinking": f"The user asks: {q[:50]}. I should answer clearly and accurately.",
})
return records
# ---------------------------------------------------------------------------
# Write output
# ---------------------------------------------------------------------------
def build_synth_dataset() -> int:
all_records: list[dict] = []
all_records.extend(_math_records())
all_records.extend(_thai_records())
all_records.extend(_en_records())
all_records.extend(_reasoning_records())
all_records.extend(_cs_records())
all_records.extend(_dialogue_records())
random.shuffle(all_records)
OUT.parent.mkdir(parents=True, exist_ok=True)
count = 0
with open(OUT, "w", encoding="utf-8") as f:
for rec in all_records:
if rec.get("question") and rec.get("answer"):
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
count += 1
print(f"Synthetic dataset: {count:,} records → {OUT}")
return count
if __name__ == "__main__":
n = build_synth_dataset()
print(f"Total training records: {n:,}")

Xet Storage Details

Size:
22.3 kB
·
Xet hash:
59d971da66647d9396862cfa9dcf89f3bc62cd63f6dfaf98ef388b75233a0b8a

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.