The dataset viewer is not available for this dataset.
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
HierLegalBERT
Hierarchical Legal BERT for Indian Supreme Court Judgment Analysis
Multi-Task Learning · Hierarchical Attention · Indian Legal NLP · OpenNyaya Corpus
Abstract
Existing legal NLP models treat court judgments as flat token sequences, truncating or ignoring the vast majority of a typical 5–15 page Indian Supreme Court judgment. HierLegalBERT is a hierarchical BERT variant that explicitly models the structural hierarchy of Indian Supreme Court judgments — preamble, facts, arguments, analysis, and order — through a two-level encoder architecture.
A sentence-level BERT encoder with novel script-type embeddings encodes each sentence independently. A document-level transformer with section-type positional encoding then reasons across all sentences with awareness of their structural role in the judgment. Four task heads — NER, clause classification, judgment prediction, and contradiction detection — are trained jointly using Kendall et al. uncertainty-weighted multi-task learning, eliminating manual loss tuning.
Trained on 19,000+ Indian Supreme Court judgments from the OpenNyaya corpus (1950–2023), HierLegalBERT provides a reproducible, publicly available baseline for Indian legal NLP.
Why HierLegalBERT? Limitations of Standard LegalBERT
Standard LegalBERT and its variants (InLegalBERT, InCaseLaw-BERT) are fine-tuned BERT models applied directly to legal text. While effective for short-document tasks, they suffer from three fundamental architectural limitations when applied to Indian Supreme Court judgments.
| Limitation | How HierLegalBERT Addresses It |
|---|---|
| Flat 512-token limit. A typical SC judgment has 5,000–15,000 tokens. LegalBERT silently discards everything beyond ~380 words of a 10-page judgment. | Hierarchical encoding processes every sentence independently then reasons across all of them. A 200-sentence judgment is fully represented with no truncation. |
| No structural awareness. LegalBERT treats a preamble sentence and an order section sentence identically. The structural role of text — facts vs. arguments vs. holding — is invisible. | Section-type positional encoding gives every sentence a learned embedding for its structural role. The model explicitly knows it is reading the Order section vs. the Facts section. |
| Single-task fine-tuning. Existing models are fine-tuned for one task at a time. A LegalBERT for NER shares no parameters with one for judgment prediction, despite the shared legal reasoning. | Uncertainty-weighted MTL trains NER, clause classification, judgment prediction, and contradiction detection simultaneously from one shared encoder. |
| Generic token representations. LegalBERT has no concept of the difference between a statutory citation (Section 302 IPC), a monetary amount (Rs. 48,000), and ordinary prose. | Script-type embeddings add a fourth learned embedding table distinguishing legal terms, numeric/monetary/date tokens, and general text at the input stage. |
| No Indian legal corpus. Most LegalBERT variants are trained on US or European legal text. Indian legal language has distinct vocabulary, citation formats, and bilingual structure. | Trained exclusively on 19,000+ Indian Supreme Court judgments from OpenNyaya (1950–2023), covering IPC sections, SCC/AIR/SCR citations, and Indian legal phrasing. |
Architecture
HierLegalBERT processes a judgment through two hierarchical encoding levels followed by four task-specific heads. All novel components are trainable layers added on top of pretrained bert-base-uncased weights.
Input Judgment
│
▼
┌─────────────────────────────────────────────────────────┐
│ LEVEL 1 — Sentence Encoder │
│ │
│ For each sentence independently: │
│ │
│ [word_emb + pos_emb + seg_emb + script_type_emb] │ ← Novel: 4th embedding table
│ │ │
│ BERT-base encoder (12 layers) │
│ │ │
│ [CLS] vector + token hidden states │
└─────────────────────────────────────────────────────────┘
│ stack [CLS] vectors across all sentences
▼
┌─────────────────────────────────────────────────────────┐
│ LEVEL 2 — Document Encoder │
│ │
│ cls_vectors + section_type_embeddings │ ← Novel: structural position
│ │ │
│ [doc_CLS] + sentence sequence │
│ │ │
│ 4-layer Transformer Encoder (cross-sentence) │
│ │ │
│ doc_cls_out sent_vectors[0..S] │
└─────────────────────────────────────────────────────────┘
│
├──────────────────┬────────────────┬──────────────────┐
▼ ▼ ▼ ▼
NER Head Clause Head Judgment Head Contradiction Head
(token-level) (sent-level) (doc-level) (pair-level)
Level 1 — Sentence Encoder
Base: bert-base-uncased (110M parameters) modified at the embedding stage.
Novel Component 1: Script-Type Embedding
BERT's standard input sums three embedding tables: word, position, and segment. HierLegalBERT adds a fourth learned table with three entry vectors:
| Type | Tokens | Examples |
|---|---|---|
| 0 — Legal | Statutory refs, citations, Latin phrases, party roles | Section 302, AIR 1999, mens rea, petitioner, respondent |
| 1 — Numeric | Monetary amounts, dates, years, large numbers | Rs. 48,000, 12/03/2019, 1987, 3,50,000 |
| 2 — General | All remaining tokens (~95% of corpus) | the, however, therefore, court, held |
Token type assignments are produced by the data pipeline using regex matching — no human annotation required. The embedding table is initialised near-zero (std=0.01) to avoid disrupting pretrained BERT weights at the start of fine-tuning.
Combined embedding (the novel input stage):
combined = word_emb + pos_emb + seg_emb + script_type_emb
combined = LayerNorm(combined)
Output per sentence: a [CLS] vector of dimension 768 representing the sentence's meaning, plus per-token hidden states [T, 768] for the NER head.
Level 2 — Document Encoder
A 4-layer transformer encoder (built from scratch, not pretrained) that operates on the sequence of sentence [CLS] vectors from Level 1. For a judgment with 80 sentences, Level 2 receives a sequence of 80 × 768-dimensional vectors.
Novel Component 2: Section-Type Positional Encoding
Instead of standard sinusoidal or absolute position embeddings, HierLegalBERT adds learned section-type embeddings to each sentence vector before the document encoder:
| ID | Section | Role |
|---|---|---|
| 0 | Preamble | Case title, bench, jurisdiction, appeal number |
| 1 | Facts | Narrative of events, parties, background |
| 2 | Arguments | Submissions of counsel, contentions raised |
| 3 | Analysis | Court's reasoning, citation of precedents |
| 4 | Order | Final disposal, costs, directions |
Two sentences at positions 25 and 75 that both belong to the Analysis section receive the same section-type embedding regardless of their absolute sequential position. This encodes structural role rather than sequential position — a meaningful distinction in hierarchically structured legal documents.
A learnable document [CLS] token is prepended to the sentence sequence. After the transformer, this vector serves as a compressed representation of the entire judgment for the judgment prediction head.
Double masking: Document-level padding (batching judgments of different lengths) is handled by a separate src_key_padding_mask applied to the document encoder, independent of the token-level attention mask in Level 1.
Task Heads
All four heads share the same encoder. Task-specific parameters are confined to the head layers.
| Head | Input | Architecture | Output |
|---|---|---|---|
| NER | Level 1 token hidden states [B, S, T, H] |
Dropout(0.1) → Linear(H, 11) |
BIO tag per token: O, B/I-PARTY, B/I-COURT, B-IPC, B/I-DATE, B/I-CITATION |
| Clause Classification | Level 2 sentence vectors [B, S, H] |
Dropout(0.1) → Linear(H, 10) |
One of 10 clause types per sentence |
| Judgment Prediction | Level 2 document [CLS] vector [B, H] |
Linear(H, H/2) → GELU → Dropout → Linear(H/2, 2) |
dismissed (0) / allowed (1) |
| Contradiction Detection | Level 2 sentence vector pairs | concat(a, b, a−b, a×b) → Linear(4H, H) → GELU → Dropout → Linear(H, 3) |
contradict / entail / neutral |
Clause categories (10 classes):
bail · penalty · jurisdiction · liability · prosecution_withdrawal · tax_assets · constitutional · evidence · precedent · other
Novel Component 3: Uncertainty-Weighted Multi-Task Loss
The four task losses are combined using Kendall et al. (2018) homoscedastic uncertainty weighting. Each task i has a learnable parameter log σᵢ (initialised to 0):
Total Loss = Σᵢ [ 0.5 × exp(−2σᵢ) × Lᵢ + σᵢ ]
The model learns σᵢ values automatically. Tasks that are harder or noisier develop larger σᵢ, reducing their effective contribution to the total loss. This eliminates manual loss weight tuning — a significant practical advantage when task difficulties are not known a priori.
During training you can watch the σ values diverge:
σ_ner→ largest (noisiest task: all labels currently −100)σ_clause→ medium (10 classes, heavy imbalance)σ_judgment→ smallest (cleanest signal: binary dismissed/allowed)
Data Pipeline
HierLegalBERT_pipeline_v3.py transforms raw OpenNyaya judgment files into model-ready JSONL with all labels computed automatically. Zero human annotation required for the initial training run.
| Stage | Description |
|---|---|
| 1. Load | Walk corpus directory for .txt / .md files. Filter by word count (300–80,000 words). |
| 2. OCR cleaning | Remove SCC margin letters (A–H), scanner artifact lines, page headers, hyphenated line breaks. Apply 15 known OCR error corrections. |
| 3. Opinion splitting | Detect multi-judge bench opinions using judge name regex (handles initials, long names, CJ variants). Split into per-judge blocks. |
| 4. Section parsing | Rule-based parser assigns each sentence to one of 5 structural sections using keyword triggers + position-based fallback. Requires at least one body section (facts/arguments/analysis). |
| 5. Token type labeling | Regex assigns every token a script type (0/1/2). Fully automatic. |
| 6. Clause classification | Two-pass keyword matching: Pass 1 checks specific categories 0–7; Pass 2 checks precedent (8); default is other (9). |
| 7. Judgment label | Three-pass regex extraction: joined order sentences → sliding window sentence pairs → last 800 chars of document. Drops remand orders and ambiguous disposals. |
| 8. Contradiction mining | Extracts silver-label sentence pairs from multi-judge opinions. Filters by legal keyword overlap for substance. |
| 9. Train/val split | Stratified 85/15 split by judgment label. Outputs train.jsonl and val.jsonl directly. |
Corpus Statistics (OpenNyaya 1950–2023)
Input files: 32,877 judgment documents
Valid labeled docs: ~19,000–22,000
dismissed (0): ~60%
allowed (1): ~35%
partly allowed (2): ~5%
Total tokens: ~179 million
Legal token %: ~0.8%
Numeric token %: ~4.1%
Section coverage: >99% of documents — all 5 sections detected
Contradiction pairs: ~870 silver-label pairs from 211 multi-bench judgments
Output Format
Each document in train.jsonl / val.jsonl follows this structure:
{
"doc_id": "2019_3_245_260_EN",
"preamble": {
"case_name": "STATE OF MAHARASHTRA v. RAJENDRA JAWANMAL GANDHI",
"date": "MARCH 15, 2019",
"appeal_no": "Criminal Appeal No. 412 of 2019",
"acts_cited": ["Section 302", "Section 34 IPC"]
},
"sections": {
"preamble": [{"text": "...", "tokens": [...], "token_type_ids": [...], "clause_label": 9, "clause_name": "other"}],
"facts": [{"text": "...", "tokens": [...], "token_type_ids": [...], "clause_label": 0, "clause_name": "bail"}],
"arguments": [...],
"analysis": [...],
"order": [...]
},
"judgment_label": 0,
"judge_opinions": ["court"],
"primary_judge": "court"
}
Training
Hardware
| Setting | Value |
|---|---|
| Minimum GPU | NVIDIA T4 16GB (Kaggle/Colab free tier) |
| Recommended GPU | NVIDIA P100 16GB (Kaggle P100 session) |
| Estimated VRAM | ~4–6 GB with gradient checkpointing enabled |
| Training time (P100) | ~8–12 minutes per epoch on 19K documents |
| Effective batch size | 8 (BATCH_SIZE=4 × ACCUM_STEPS=2) |
Hyperparameters
| Hyperparameter | Value | Rationale |
|---|---|---|
| BERT learning rate | 2e-5 |
Standard BERT fine-tuning range |
| Novel layers LR | 1e-5 |
Conservative: novel layers need lower LR to not disrupt BERT |
| Optimizer | AdamW | Weight decay decoupled from adaptive LR |
| Weight decay | 0.01 |
Standard regularisation |
| Gradient clipping | 1.0 |
Prevents explosion from novel layer gradients in early epochs |
| Scheduler | OneCycleLR | 10% warmup + cosine decay |
| Mixed precision | fp16 | AMP on GPU; automatic fallback on CPU |
| Gradient checkpointing | Enabled on BERT encoder | ~40% VRAM reduction, trades compute |
| Early stopping | patience=3 | Stops on val loss plateau |
| Max sentences | 30 per document | Covers ~95% of judgments; fits P100 |
| Max tokens | 128 per sentence | SC sentences average ~35 tokens |
Two-Group Optimizer
BERT parameters and novel layer parameters use separate learning rates:
optimizer = AdamW([
{"params": bert_params, "lr": 2e-5}, # preserve pretrained representations
{"params": novel_params, "lr": 1e-5}, # novel layers: script emb, section enc, doc encoder, heads
])
This prevents novel layers — which have large initial gradients from random initialisation — from destabilising the pretrained BERT weights in early training.
Quick Start
Step 1 — Data Preparation
# Add OpenNyaya dataset as input, then:
python HierLegalBERT_pipeline_v3.py
Expected output: train.jsonl (16K docs), 3K docs), val.jsonl (contradiction_pairs.jsonl, pipeline_stats.json
Step 2 — Training
# Set at top of HierLegalBERT_train_v2.py:
TRAIN_PATH = "/kaggle/working/train.jsonl"
VAL_PATH = "/kaggle/working/val.jsonl"
JUDGMENT_MODE = "binary" # recommended until more "partly" data available
python HierLegalBERT_train_v2.py
Expected outputs: checkpoints/HierLegalBERT_best.pt, plots/loss_curves.png, plots/f1_curves.png
Step 3 — Verify Architecture (optional)
# Smoke test: forward + backward pass on synthetic toy data
# No corpus needed, runs in <30 seconds on CPU
python HierLegalBERT_prototype.py
Expected output: all shape assertions pass, loss is finite, all novel parameter gradients are non-zero.
Novel Contributions Summary
Three components distinguish HierLegalBERT from prior work and form the basis of the ablation study:
Contribution 1 — Script-Type Embeddings (domain-specific input representation)
- A fourth embedding table summed into BERT's standard word+position+segment embeddings
- No prior legal NLP model distinguishes legal citation tokens from numeric tokens from general prose at the input representation level
- Ablation: remove script-type embeddings → expected NER F1 drop of ~3–5 points on citation and IPC entities
Contribution 2 — Section-Type Positional Encoding (structural document awareness)
- Learned section-type embeddings (5 types) added to sentence vectors before the document encoder
- Prior hierarchical NLP models use absolute or relative position; HierLegalBERT uses structural role (facts vs. arguments vs. order) as the positional signal
- Ablation: replace with sinusoidal absolute position → expected judgment prediction F1 drop (relies heavily on order section signal)
Contribution 3 — Uncertainty-Weighted 4-Task MTL (principled multi-task balancing)
- Kendall et al. uncertainty weighting with learnable log-sigma per task, replacing manual loss weights
- Prior legal NLP MTL papers either train tasks separately or use fixed manual weights; uncertainty weighting is self-regulating and principled
- Ablation: replace with equal manual weights → expected training instability or underperformance on harder tasks
Expected Results
Baseline after 10 epochs on OpenNyaya corpus with binary judgment mode:
| Task | Metric | Baseline | Notes |
|---|---|---|---|
| Judgment Prediction | Macro F1 | 0.55–0.65 | Binary mode (dismissed/allowed). Improves with more epochs. |
| Clause Classification | Macro F1 | 0.35–0.50 | 10 classes with heavy imbalance. Constitutional and bail classes learn fastest. |
| NER | Macro F1 | 0.00 | No ground-truth NER labels yet. Replace aligned_ner = [-100]*T in dataset with real BIO labels to activate. |
| Contradiction Detection | Macro F1 | 0.00 | No contradiction pairs in standard batches. Activates when contra_pairs populated per document. |
| σ values | — | σ_ner > σ_clause > σ_judgment | NER develops highest σ (noisiest). Judgment develops lowest (cleanest signal). |
Repository Structure
HierLegalBERT/
├── HierLegalBERT_pipeline_v3.py # Data preparation: OpenNyaya → train.jsonl + val.jsonl
├── HierLegalBERT_train_v2.py # Full training script with all architecture components
├── HierLegalBERT_prototype.py # Architecture smoke test on synthetic toy data
├── nan_debug.py # Diagnostic script for NaN loss debugging
├── README.md # This file
├── .gitignore # Excludes corpus, checkpoints, plots, weights
└── checkpoints/ # Model checkpoint directory (git-ignored)
Key References
- Devlin et al. (2019) — BERT: Pre-training of Deep Bidirectional Transformers
- Chalkidis et al. (2020) — LEGAL-BERT: The Muppets straight out of Law School
- Kendall et al. (2018) — Multi-Task Learning Using Uncertainty to Weigh Losses
- Yang et al. (2016) — Hierarchical Attention Networks for Document Classification
- Paul et al. (2022) — Pre-training Transformers on Indian Legal Text (InLegalBERT)
- Ghosh et al. (2021) — ILDC for CJPE: Indian Legal Documents Corpus
- OpenNyaya (2024) — Indian Supreme Court Judgments 1950–2023, Kaggle / AWS Open Data
HiLegalBERT — IIT Kharagpur · Industrial and Systems Engineering
- Downloads last month
- 15,404