/ Модель

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

Лицензия
Apache 2.0
Архитектура
looped_transformer · dense
Библиотека
mlx
Опубликована
15 ноя 2026

Looped-Transformer-485M-Indian-Law-Thinking

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

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

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

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

Suvir Misra разработал эту языковую модель на 485,1 млн параметров для анализа индийского законодательства и судебной аргументации. Она использует рекуррентную архитектуру LoopedTransformerLM: 8 физических слоёв проходят три цикла вычислений, что даёт виртуальную глубину в 24 слоя. Модель рассчитана на контекст до 4 096 токенов и работает с библиотекой Apple MLX; веса опубликованы в формате Safetensors.

Модель дообучена на вопросах и ответах по индийскому праву, включая Конституцию, BNS 2023, CPC 1908, налог на доходы и GST. Она формирует промежуточные рассуждения в формате Chain-of-Draft, чтобы структурировать расчёты, ссылки на нормы и проверку исключений. Её предполагаемые сценарии — локальный юридический помощник и анализ, основанный на документах и RAG.

Модель поддерживает генерацию текста на английском языке. Она может ошибаться в юридических ссылках и выводах, поэтому для значимых решений необходима проверка человеком и сверка с источниками. Лицензия — Apache-2.0.

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

  • ответы на вопросы по индийскому конституционному праву
  • поиск применимых норм BNS, CPC, налогового законодательства и GST
  • подготовка чернового анализа судебных вопросов
  • проверка юридических выводов по документам в RAG-системе

Ограничения

Модель небольшая и может ошибаться в юридических ссылках и выводах; для высокозначимых задач необходимы проверка человеком и сверка с документами через RAG.

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

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

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

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

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

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

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

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

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

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

Открыть на Hugging Face

Looped Transformer SLM (485M): Indian Law & Chain-of-Draft Thinking

A native Apple MLX recurrent-depth ("looped") language model specifically fine-tuned and aligned for Indian Statutory Law, Procedure, and Judicial Reasoning with explicit Chain-of-Draft <think>...</think> scratchpad tokens.

  • Architecture: Recurrent-Depth Transformer (LoopedTransformerLM)
  • Physical Parameters: 485.1 Million (~1.8 GB FP16 weights)
  • Virtual Computational Depth: 24 layers (8 physical layers $\times$ 3 recurrent loops)
  • Context Window: 4,096 tokens
  • Reasoning Mechanism: Chain-of-Draft (CoD) structured intermediate thinking traces

1. Architectural Highlights

Unlike standard linear feedforward transformers, this model stores 8 physical transformer layers and loops the recurrent hidden state through them 3 times per forward pass.

[Token x] ──> Embedding ──> [Loop 1: 8 Layers] ──> Reinject Adapter ──> [Loop 2: 8 Layers] ──> Reinject Adapter ──> [Loop 3: 8 Layers] ──> lm_head
                                 │                                           │                                           │
                        Shared Weights (W)                          Shared Weights (W)                          Shared Weights (W)

Key Mechanisms:

  1. Input-Embedding Re-Injection: The original token embedding is projected and re-injected at the beginning of each loop iteration to prevent signal fading across recurrence.
  2. Per-Loop Depth Embeddings: A learned timestep embedding indexed by loop iteration ($0, 1, 2$) allows the shared physical layers to specialize behavior across early vs. late computational depth.
  3. Sandwich Normalization: RMSNorm is applied before and after both self-attention and SwiGLU FFN blocks (4 norms per layer) to bound residual stream growth across recurrence.

2. Multi-Stage Training Pipeline

  1. Balanced SFT & Grounding:
    • IndicLegalQA: Ingested 9,579 substantive Supreme Court QA pairs from the revised IndicLegalQA dataset.
    • Statutory Precision: Grounded Bare Act rules across the Bharatiya Nyaya Sanhita (BNS 2023), Code of Civil Procedure (CPC 1908), Income-tax Act 1961, and CGST Act 2017.
    • Anti-Collapse Replay: 2,500 Alpaca general instruction rows to prevent catastrophic forgetting and recurrent fixed-point collapse.
  2. Chain-of-Draft (CoD) Thinking SFT:
    • 100% of training rows formatted with <think>1. ... 2. ... 3. ... 4. ...</think> scratchpads.
    • Teaches the model to calculate, cite governing sections, and check exceptions before outputting the final answer.
  3. Calibrated On-Prompt ORPO (Odds Ratio Preference Optimization):
    • Contrastive pairs constructed on the identical prompt ($x, y_{\text{gold}}, y_{\text{hallucinated}}$) to suppress phantom citations (Gopantray, Marananda Bharati) without penalizing general legal syntax.
  4. TIES & Model Souping:
    • Merged optimal trajectory checkpoints using TIES trimming (35% density, 0.85 scale) to eliminate gradient noise and achieve balanced statutory precision.

3. Evaluation Benchmarks

Evaluated on the 16-point Indian Legal & Procedural Benchmark Suite (scripts/eval_legal_thinking.py):

Test IDLegal DomainSubject & Statute TestedStatute MatchThinking Trace ()Status
CONST_01Constitutional LawBasic Structure (Kesavananda Bharati, Art 368)100%Opened & ClosedPASSED
CONST_02Constitutional LawArticle 21 (Maneka Gandhi, Life & Liberty)100%Opened & ClosedPASSED
CONST_03Constitutional LawMinerva Mills (1980) (Balance FRs & DPSPs)75%Opened & ClosedPASSED
CONST_04Constitutional LawLok Sabha Minimum Age (Article 84(b) - 25 yrs)100%Opened & ClosedPASSED
CRIM_01Criminal JurisprudenceMaxim Actus non facit reum nisi mens sit rea100%Opened & ClosedPASSED
CRIM_02Criminal Law (BNS 2023)Petty Offenses Punishment: Community Service (Sec 4(f))100%Opened & ClosedPASSED
CRIM_03Criminal Law (BNS 2023)Infancy Immunity: Child under 7 years (Sec 20 doli incapax)100%Opened & ClosedPASSED
CPC_01Civil Procedure CodeDecree (Sec 2(2) substantive) vs. Order (Sec 2(14))80%Opened & ClosedPASSED
CPC_02Civil Procedure CodeConclusiveness of Foreign Judgments (Sec 13 CPC, Satya)100%Opened & ClosedPASSED
CPC_03Civil Procedure CodePleadings Rules under Order VI Rule 2 (Facts not law)50%Opened & ClosedPASSED
TAX_01Income Tax Act, 1961Tax Residence (Section 6(1) - 182d / 60+365d tests)100%Opened & ClosedPASSED
TAX_02Income Tax Act, 1961Five Heads of Income (Section 14)100%Opened & ClosedPASSED
TAX_03Income Tax Act, 1961Professional TDS Rate & Threshold (Section 194J - 10% > ₹30k)100%Opened & ClosedPASSED
GST_01Central GST Act, 2017Time of Supply of Goods (Section 12 forward/reverse charge)75%Opened & ClosedPASSED
COMM_01Negotiable InstrumentsCheque Bouncing Criminal Penalty (Section 138 - 2 yrs / double)67%Opened & ClosedPASSED
PERS_01Personal Law (Muslim)Testamentary Succession Wasiyat (Rule of One-Third / 1/3rd)100%Opened & ClosedPASSED
  • Overall Pass Rate: 16 / 16 (100.0%)
  • <think> Trace Opened Rate: 16 / 16 (100.0%)
  • </think> Trace Closed Rate: 16 / 16 (100.0%)

4. Quickstart Guide (Local Inference with MLX)

Installation

pip install mlx tokenizers huggingface_hub

Running Inference via CLI

# Clone the repository
git clone https://huggingface.co/Suvir-Misra/Looped-Transformer-485M-Indian-Law-Thinking
cd Looped-Transformer-485M-Indian-Law-Thinking

# Run a query
python generate.py "Under Section 6(1) of the Income-tax Act, 1961, when does an individual qualify as a resident?"

Python API Example

import mlx.core as mx
from generate import load_model, generate

# Load model and custom BPE tokenizer
model, tok, cfg = load_model(".")

prompt = "What does the fundamental criminal law maxim 'Actus non facit reum nisi mens sit rea' mean?"
response = generate(model, tok, cfg, prompt, max_new=220, temp=0.2)
print(response)

Example Output:

<think>
1. Translate Latin maxim: an act does not make one guilty without a blameworthy mind.
2. Identify first essential element: Actus Reus (wrongful physical act/omission).
3. Identify second essential element: Mens Rea (culpable mental state/guilty mind).
4. State fundamental principle of criminal liability.
</think>

The fundamental legal maxim **'Actus non facit reum nisi mens sit rea'** translates to: **'An act does not make one guilty unless the mind is also blameworthy'**.

It establishes the cardinal principle of criminal jurisprudence that criminal liability requires two concurrent elements:
1. **Actus Reus**: The commission of a prohibited physical wrongful act or omission.
2. **Mens Rea**: A culpable, blameworthy mental state (intent, knowledge, or criminal recklessness).[EOS]

5. Deployment & Limitations

  • Intended Use: On-premise legal edge copilot, statutory threshold validation, and RAG-grounded legal analysis for Indian law.
  • Limitations: Like all small language models (485M parameters), this model should not be deployed as an unconstrained legal counsel without human review or document-grounded RAG verification for high-stakes litigation.

6. Citation

@misc{misra2026loopedtransformer,
  author = {Suvir Misra},
  title = {Looped Transformer SLM: Recurrent-Depth Indian Legal Reasoning with Chain-of-Draft Thinking},
  year = {2026},
  publisher = {Hugging Face},
  howpublished = {\url{https://huggingface.co/Suvir-Misra/Looped-Transformer-485M-Indian-Law-Thinking}}
}

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

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

GPU в ailist

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

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

MLX-модели работают только на Apple Silicon, на GPU NVIDIA они не запускаются.

Класс архитектуры
LoopedTransformerLM
Ревизия весов
9ec5e33

0 моделей