/ Модель

Характеристики

Лицензия
MIT
Архитектура
custom-khmer-food-lm · dense
Библиотека
pytorch
Опубликована
26 сен 2026

khmer-food-lm

Генерация текстаТекст → текст3 профессии
40скачиваний за 30 дней0лайковвеса обновлены26 сен 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Небольшая обученная с нуля модель Transformer для экспериментов с генерацией кхмерского текста о камбоджийской еде.

Khmer Food LM — небольшая языковая модель, созданная Chhorn Seyha с нуля для обучения и экспериментов. Она использует авторскую архитектуру декодера Transformer с причинным вниманием и обучалась в PyTorch предсказывать следующий токен; модельные веса хранятся в формате safetensors. Параметры включают размер эмбеддингов 64, два слоя Transformer, словарь SentencePiece BPE из 200 токенов и максимальную длину последовательности 160 токенов.

Модель предназначена для генерации текста на кхмерском языке о камбоджийской кухне: названиях блюд, ингредиентах, категориях, вкусах и типах приёма пищи. Она обучена с нуля на небольшом наборе из 40 блюд, дополненном вопросами и ответами; это учебный проект, а не универсальная языковая модель. Лицензия — MIT.

Из-за малого объёма данных и модели текст может быть грамматически некорректным, повторяться или содержать вымышленные сведения об ингредиентах и блюдах. Модель может плохо работать с блюдами, отсутствовавшими в обучающих данных, и не подходит как надёжный источник сведений о кухне или безопасности пищевых продуктов.

Сценарии применения

  • генерация описаний камбоджийских блюд на кхмерском языке
  • создание вопросов и ответов об ингредиентах блюд
  • эксперименты с генерацией текста на кхмерском языке
  • обучение работе с токенизацией SentencePiece и причинным Transformer

Ограничения

Модель обучена на небольшом наборе данных о 40 блюдах и может повторять фразы, генерировать грамматически некорректный текст или выдумывать ингредиенты. Она не предназначена для производственного применения и не является надёжным источником сведений о кухне или безопасности пищевых продуктов.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Khmer Food LM — From Scratch

Model Description

Khmer Food LM is a small custom language model built from scratch for learning and educational purposes. It is designed to experiment with understanding and generating Khmer text related to Cambodian food, including food names, descriptions, ingredients, categories, tastes, and meal types.

The main goal of this project is not to build a production-ready language model. It was created to learn the complete process of building a language model from raw data to a trained model.

Instead of fine-tuning an existing foundation model, the model is initialized with random weights and trained using a custom PyTorch Transformer architecture.

  • Developed by: Chhorn Seyha
  • Model type: Causal Language Model
  • Framework: PyTorch
  • Primary language: Khmer (km)
  • Domain: Cambodian food
  • Purpose: Learning / Educational
  • License: MIT
  • Architecture: Custom Transformer Decoder

Learning Purpose

This project was created specifically to understand how language models work internally.

The project covers the complete pipeline:

Raw food data
    ↓
Manual data cleaning
    ↓
Data validation
    ↓
Question-answer augmentation
    ↓
Food-level Train / Validation / Test split
    ↓
Tokenizer training
    ↓
Token embeddings
    ↓
Causal self-attention
    ↓
Transformer blocks
    ↓
Next-token prediction
    ↓
Model training
    ↓
Evaluation
    ↓
Text generation

The project was intentionally built from basic components instead of relying on a pretrained language model.

Dataset

The current dataset contains information about 40 Cambodian food entries.

Each food record can contain:

  • Khmer food name
  • English food name
  • Description
  • Category
  • Ingredients
  • Taste
  • Meal type

Question-answer variations are generated from these structured records for language-model training.

The current food-level split is:

SplitFoodsGenerated Examples
Train28418
Validation686
Test690
Total40594

The split is performed at the food level before augmentation. This helps prevent question variations about the same food from appearing in both training and evaluation data.

Tokenizer

The model uses a custom SentencePiece BPE tokenizer trained on the project's Khmer training corpus.

Configuration:

  • Tokenizer: SentencePiece
  • Model: BPE
  • Vocabulary size: 200
  • Character coverage: 1.0
  • PAD ID: 0
  • UNK ID: 1
  • BOS ID: 2
  • EOS ID: 3

Example:

Input:
នំបញ្ចុកមានគ្រឿងផ្សំអ្វីខ្លះ?

Example subword pieces:
['▁', 'ន', 'ំប', 'ញ', '្', 'ច', 'ុក', 'មាន', 'គ្រឿងផ្សំ', 'អ្វី', 'ខ', '្ល', 'ះ', '?']

The exact segmentation depends on the vocabulary learned from the training corpus.

Model Architecture

Khmer Food LM uses a small custom causal Transformer written in PyTorch.

Current configuration:

  • Embedding size: 64
  • Transformer layers: 2
  • Feed-forward hidden size: 256
  • Tokenizer vocabulary: 200
  • Maximum sequence length: 160
  • Attention: Causal self-attention
  • Normalization: LayerNorm
  • Activation: ReLU
  • Training objective: Next-token prediction

Causal masking prevents each token from looking at future tokens during training.

Training

The model is trained from random initialization.

Training configuration:

  • Framework: PyTorch
  • Optimizer: AdamW
  • Learning rate: 0.001
  • Epochs: 20
  • Batch size: 4
  • Loss: Cross-entropy
  • Padding tokens: Ignored during loss calculation
  • Training device: CUDA when available

The model learns next-token prediction using:

Input:
Token 1 → Token 2 → Token 3 → ...

Target:
Token 2 → Token 3 → Token 4 → ...

Evaluation

An earlier character-level version trained on the 40-food dataset produced:

SplitLoss
Train0.5466
Validation1.6231
Test1.3960

These values belong to the earlier character-tokenizer experiment and should not be interpreted as the final SentencePiece model results.

The SentencePiece model should be evaluated separately so the two tokenizer approaches can be compared fairly.

Model Files

model.safetensors
khmer_food_spm.model
khmer_food_spm.vocab
model.py
config.json
README.md

model.safetensors contains the trained model weights.

khmer_food_spm.model contains the SentencePiece tokenizer model.

model.py contains the model architecture plus helpers to load the model and generate text.

How to Use

pip install torch sentencepiece safetensors huggingface_hub
import sys
from huggingface_hub import snapshot_download

model_dir = snapshot_download("seyhachhorn/<repo-name>")
sys.path.insert(0, model_dir)

from model import load_model, generate

model, tokenizer = load_model(model_dir)

print(generate(model, tokenizer, "នំបញ្ចុកសម្លការីគេនិយមញ៉ាំនៅពេលណា?"))

Prompts use the same format as the training data:

សំណួរ: <question>
ព័ត៌មានបន្ថែម: <optional context>
ចម្លើយ:

Limitations

This model is an educational experiment and is not intended for production use.

The dataset and model are both very small compared with modern language models.

The model may:

  • generate incorrect Khmer text
  • repeat words or phrases
  • hallucinate ingredients
  • provide incorrect information about Cambodian dishes
  • fail on foods that were not represented during training
  • produce grammatically incorrect sentences
  • memorize patterns from the training dataset instead of learning broad language understanding

The model should therefore not be treated as an authoritative source for Cambodian cuisine or food safety information.

Why Build From Scratch?

Modern language models are usually trained on billions or trillions of tokens.

This project deliberately uses a tiny dataset and model so that each component can be understood and implemented manually.

The goal is to learn concepts such as:

Tokenization
Embedding
Position embedding
Query / Key / Value
Self-attention
Causal masking
Feed-forward networks
Transformer blocks
Logits
Cross-entropy loss
Backpropagation
Next-token generation

Future Improvements

Possible future experiments include:

  • Expanding from 40 to 100+ Cambodian foods
  • Adding more natural Khmer training text
  • Increasing SentencePiece vocabulary
  • Increasing Transformer depth
  • Increasing embedding dimensions
  • Multi-head attention
  • Dropout
  • Early stopping
  • Better generation strategies such as temperature and top-k sampling
  • Comparing character and subword tokenization
  • Publishing the dataset separately on Hugging Face

Disclaimer

Khmer Food LM is built for learning and educational purposes.

It is a small experimental language model trained from scratch and should not be considered a production-ready AI system or a reliable source of factual food information.

Author

Chhorn Seyha

Hugging Face: seyhachhorn

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · pytorch

Нельзя запустить

Архитектура custom-khmer-food-lm неизвестна transformers в образе рантайма.

Ревизия весов
39ff7da

0 моделей