diff --git a/track_2a/.env.example b/track_2a/.env.example index 233d7a2..3ab0cf5 100644 --- a/track_2a/.env.example +++ b/track_2a/.env.example @@ -1,4 +1,4 @@ BASE_URL=https://api.inference.cscs.ch/v1 API_KEY= MAX_OUTPUT_TOKENS=500 -DATA_DIR=data/sample \ No newline at end of file +DATA_DIR=data/ \ No newline at end of file diff --git a/track_2a/.gitignore b/track_2a/.gitignore index 3e0eb92..ce9ea80 100644 --- a/track_2a/.gitignore +++ b/track_2a/.gitignore @@ -27,6 +27,7 @@ logs/ analysis/ data/full data/dev_a/ +data/batches/* data/dev_b/ data/test_a/ data/test_b/ diff --git a/track_2a/docs/Decisions.md b/track_2a/docs/Decisions.md new file mode 100644 index 0000000..4e2244b --- /dev/null +++ b/track_2a/docs/Decisions.md @@ -0,0 +1,100 @@ +# Design Decisions + +This document records the reasoning behind the final Track 2A pipeline. It focuses on the alternatives considered, the trade-offs involved, and why particular approaches were selected or retained. + +## 1. PDF Parsing and Source Preparation + +**Decision:** Use PyMuPDF to extract page-level text while preserving page numbers and the original text needed for evidence verification. + +**Alternatives considered:** Basic text extraction, paragraph-level processing, and more complex layout-aware parsing. + +**Rationale:** Page-level extraction provides a practical balance between preserving document structure and keeping preprocessing lightweight. Original extracted text is retained separately from normalized text so that matching can tolerate PDF artifacts without changing the evidence returned to the evaluator. + +Complex layout-aware processing was not made a default dependency because it would increase setup and runtime costs without an established improvement sufficient to justify the added complexity. + +## 2. Selecting Relevant Pages + +**Decision:** Use the voting proposal and document structure to narrow the search space before retrieving evidence. + +**Rationale:** Searching an entire booklet introduces irrelevant passages, particularly when a booklet contains multiple voting proposals. Restricting retrieval to the relevant proposal reduces the search space and avoids mixing evidence belonging to different votes. + +The selection process uses proposal-title matching and page-level signals, with neighboring-page context and fallback behavior to reduce the risk of excluding relevant evidence. + +**Trade-off:** Aggressive filtering can reduce token usage but may remove the page containing the required fact. Page-selection quality therefore needs to be assessed alongside classification performance. + +## 3. Chunking Strategy + +**Decision:** Use sentence-level units with page metadata for retrieval, while retaining enough surrounding context to reconstruct meaningful passages. + +**Alternatives considered:** Fixed-size windows, paragraph-level chunks, and sentence-level retrieval. + +**Rationale:** Fixed windows are simple but can split facts, qualifications, or negations across boundaries. Paragraphs preserve more context but may contain irrelevant information. Sentence-level units offer more precise matching for short factual claims and support direct evidence identification. + +Neighboring sentences are included when necessary so that retrieved evidence does not lose its original meaning. + +## 4. Retrieval Strategy + +**Decision:** Combine lexical and semantic retrieval rather than relying exclusively on either method. + +**Alternatives considered:** Full-document context, lexical retrieval using BM25, dense multilingual retrieval, and hybrid retrieval. + +**Rationale:** BM25 is useful when claims and source passages share exact terms, names, dates, or numbers. Dense multilingual embeddings can identify semantically related passages even when the claim and booklet use different wording or languages. + +The hybrid approach combines these complementary signals using Reciprocal Rank Fusion (RRF). This avoids relying entirely on one ranking method and supports the multilingual nature of the task. + +The local multilingual embedding model was selected to avoid depending on a separate embedding API at inference time. The added model size and CPU processing cost remain important trade-offs. + +## 5. Context Construction + +**Decision:** Send selected source passages to Apertus instead of treating retrieval results as an unordered collection of isolated sentences. + +**Rationale:** A passage can be relevant lexically but insufficient to establish entailment or contradiction without its surrounding qualifiers, actor, or recommendation. Neighboring context helps preserve these relationships. + +The final context is assembled within an input-character budget, with source and page information retained for evidence traceability. + + +## 6. Classification Prompts and Model Configuration + +**Decision:** Use task-specific instructions and structured classification output, with separate configurations for Task A and Task B. + +- **Task A:** Classify claims against retrieved voting-booklet context and return supporting evidence. +- **Task B:** Classify claims against the supplied reference text without unnecessary PDF retrieval. + +The prompts explicitly distinguish entailment, neutral, and contradiction. They emphasize actor attribution, polarity, numerical details, and the difference between a claim being unsupported and being contradicted. + +**Model configuration:** Task A uses Apertus v1.5 70B, while Task B uses Apertus v1.5 8B. + +**Rationale:** The tasks provide different amounts and types of context, so they do not require identical processing paths. Explicit classification rules also help prevent the model from treating missing information as proof of contradiction. + +Prompt variants, model choices, and other experimental changes should be compared using the corresponding experiment reports rather than assumed to be improvements. + +## 7. Evidence Verification + +**Decision:** Verify generated evidence against the original source instead of trusting model-produced quotations directly. + +**Rationale:** A correct label can still produce invalid evidence if a quotation is paraphrased, fabricated, assigned to the wrong page, or affected by PDF line-break hyphenation. + +The verification process tolerates common text-extraction differences while mapping matched evidence back to the original page text. When a required quotation cannot be verified, the pipeline uses its defined fallback behavior rather than returning an unverified quotation as if it were exact. + +Task B evidence is also checked against its reference text; page numbers are not applicable to that task. + +**Trade-off:** Strict verification improves evidence reliability but can reject legitimate quotations when extraction differs substantially from the source. Evidence quality and classification quality must therefore be considered separately. + +## 8. Failure Handling and Output Reliability + +**Decision:** Validate model output, handle inference or parsing failures, and maintain the required prediction structure for each input case. + +**Rationale:** Model responses may contain malformed JSON, unexpected label formats, or no usable answer. Network errors and missing source files can also interrupt processing. + +The pipeline uses parsing and validation, bounded retry behavior where applicable, and a defined neutral fallback for failures that cannot be recovered. Token usage and inference timing are retained where available so that failures do not disappear from performance analysis. + +This prioritizes predictable execution and output-contract compliance over allowing one problematic case to terminate an entire run. + +## 9. How Final Decisions Were Evaluated + +Design choices are not considered improvements solely because they make the architecture more sophisticated. + +The evaluation process uses the official `evaluate.py` script from the Hackstarter repository. Experiments are compared using the same evaluation procedure, with attention to classification quality, token usage, inference time, evidence reliability, and failure behavior where those measurements are available. + +A change should be retained when its measured benefits justify its additional cost or complexity. Results for individual experiments are documented in the `reports/` folder. + diff --git a/track_2a/docs/README.md b/track_2a/docs/README.md index 0743f59..2d87d1b 100644 --- a/track_2a/docs/README.md +++ b/track_2a/docs/README.md @@ -11,15 +11,10 @@ This directory contains the technical documentation for Track 2A, covering setup - [Pipeline](pipeline.md) — step-by-step execution from input cases to predictions. - [Retrieval](retrieval.md) — PDF processing, text extraction, chunking, embeddings, and evidence retrieval. - [Classification](classification.md) — Apertus inference, prompts, label mapping, output parsing, and evidence requirements. -### Experiments and evaluation -- [Experiments](experiments.md) — experiment configurations, hypotheses, results, observations, and conclusions. -- [Evaluation](evaluation.md) — evaluation metrics, datasets, comparison methodology, results, and limitations. +### Evaluation - [Dataset documentation](../data/README.md) — dataset sources, input format, data layout, preparation, and split details. - [Split manifest](splits.json) — recorded development, validation, and test membership. ### Engineering and maintenance -- [Design decisions](decisions.md) — alternatives considered, selected approaches, trade-offs, and rationale. -- [Change log](changes.md) — significant implementation changes, reasons, tests, and their impact. -- [Testing](testing.md) — unit tests, integration tests, smoke tests, Docker checks, and output validation. -- [Troubleshooting](troubleshooting.md) — common errors, root causes, fixes, and verification steps. +- [Design decisions](Decisions.md) — alternatives considered, selected approaches, trade-offs, and rationale. The [project README](../README.md) provides the project overview and entry point. The [technical report](../technical_report.md) presents the consolidated account of the system and its findings, with links to the relevant documentation in this directory. \ No newline at end of file diff --git a/track_2a/docs/classification.md b/track_2a/docs/classification.md index f684e78..932bc2f 100644 --- a/track_2a/docs/classification.md +++ b/track_2a/docs/classification.md @@ -1,128 +1,110 @@ -# Classification and evidence +# Classification and Evidence -## Apertus interface +## At a glance -[`LLMClient`](../src/llm_client.py) uses the OpenAI-compatible -`chat.completions.create` interface. It sends `temperature=0`, the selected -maximum token count, a task-specific model identifier, and a strict JSON Schema -response format: +Both tasks use Apertus to compare a claim with a supplied source. The prompts prioritize **source-grounded reasoning over keyword overlap**. -- Task A: `swiss-ai/Apertus-v1.5-70B`, with structured evidence objects. -- Task B: `swiss-ai/Apertus-v1.5-8B`, with `"evidence": null`. +| | Task A — PDF booklet | Task B — Reference text | +|---|---|---| +| Input | Vote, claim, language, retrieved booklet excerpts | Vote, claim, language, supplied source passage | +| Model | `swiss-ai/Apertus-v1.5-70B` | `swiss-ai/Apertus-v1.5-8B` | +| Core task | Classify and cite source evidence | Classify only | +| Model evidence output | `[{"page": 4, "text": "verbatim quote"}]` | `null` | +| Final evidence | Verified PDF text and 1-based page | `[]` | -The endpoint is configured by `BASE_URL` (default -`https://api.inference.cscs.ch/v1`) and authenticated with `API_KEY` or its -documented alias. `MOCK_LLM=1` bypasses the API and returns intentionally fake -neutral responses for CI/container checks only. +## Shared prompt instructions -## Prompt structure and labels +The shared `RULES` in `src/prompts.py` tell the model to: -[`src/prompts.py`](../src/prompts.py) supplies a shared decision procedure. -The model must distinguish: +- **Use only the supplied source.** Do not rely on outside knowledge or plausibility. +- **Compare meaning, not wording.** Paraphrases and translations can support a claim if the essential meaning agrees. +- **Check essential details:** vote/proposal, actor, action, stance, polarity/negation, quantities, dates, conditions, attribution, and scope. +- **Require a specific conflict for contradiction.** Identify the claim's assertion and the incompatible source fact. Missing information or lack of confirmation is not contradiction. +- **Prefer neutral when unresolved.** If the source is silent, incomplete, ambiguous, or unrelated, do not invent support or conflict. +- **Decide before selecting evidence.** Avoid choosing a label to fit a loosely related passage. +- **Return valid JSON only.** No explanation outside the requested structure. -- `entailment`: the source supports the claim, including its actor, action, - polarity, quantities, dates, conditions, and scope; -- `contradiction`: the source directly conflicts with an essential claim - detail; and -- `neutral`: the source is silent, incomplete, ambiguous, unrelated, or does - not establish a required detail. +## Task A: additional evidence instructions -The numeric mapping is applied after parsing: +Task A uses `SYSTEM_A`. Its excerpts are **partial retrieved passages**, so the model must search all supplied sentences and confirm that a passage addresses the same proposition—not merely the same keyword, committee, or topic. -```text -0 -> entailment -1 -> neutral -2 -> contradiction -``` - -The prompt explicitly warns against treating missing support as contradiction, -mixing different votes or actors, confusing existing law with a proposal, and -using outside knowledge. + -## Task-specific prompt inputs +**What Task A emphasizes** -Task A receives: +- Check the exact vote and actor; never mix proposals or institutional positions. +- Compare the direction of the claim and source. A source recommending rejection can support a claim that a proposal is unsuitable. +- If no supplied passage addresses the proposition, choose neutral. +- Quote only text present in the excerpts. Do not reconstruct context or combine fragments into a fabricated quote. +- Preserve qualifications, negation, conditions, and attribution in the quote. +- Use the sentence's own `[S... p.n]` page label; page numbers are 1-based. IDs and markers are metadata, not quote text. +- For entailment/contradiction, return **1–4 useful evidence items**. Prefer the smallest set that establishes the decision. +- For neutral, return `"evidence": []`. Each quote must be at most 4,500 characters. -```text -VOTE: + -BOOKLET: -[[PAGE 4]] -[S00021 p.4] -[S00022 p.4] +Expected response: -CLAIM (language: ): +```json +{ + "label": "entailment|neutral|contradiction", + "evidence": [ + {"page": 4, "text": "verbatim source sentence"} + ] +} ``` -The system prompt says that the passages are partial excerpts, requires -verbatim evidence from supplied sentences, and requires the sentence's -1-based PDF page. Sentence IDs and page markers are metadata, not quote text. +## Task B: additional instructions -Task B receives the vote, the complete embedded `SOURCE` passage, and the claim. -It uses the same semantic decision rules but explicitly forbids evidence -generation: +Task B uses `SYSTEM_B` and the complete source passage supplied with the claim. It follows the shared decision rules, but **must not generate evidence or quotations**. ```json -{"label": "entailment|neutral|contradiction", "evidence": null} +{ + "label": "entailment|neutral|contradiction", + "evidence": null +} ``` -## Parsing and malformed responses - -[`parse_output_detailed`](../src/parsing.py) requires a JSON object with a -valid label and an `evidence` field. It rejects invalid JSON, non-object -responses, unknown labels, non-list/non-null evidence, invalid page numbers, -empty or oversized quotes, more than five items, and non-neutral labels with no -evidence. Evidence returned for a neutral label is discarded with a warning. -`null` evidence is normalized to an empty list for downstream consistency. +The pipeline normalizes Task B's `null` to `[]` in the final output. -The pipeline gives a malformed response one retry. It appends a correction -instruction naming the validation failure and asks for a complete schema-valid -JSON object. If that request fails or remains malformed, -[`_fallback`](../src/pipeline.py) emits label `1`, empty evidence, and the -available token/time metrics. The same neutral fallback covers unexpected -per-case errors such as a missing PDF. +## Decision checklist -The client itself retries transient connection, timeout, rate-limit, and -selected server errors with bounded exponential backoff. It does not retry -ordinary non-retryable client errors indefinitely. - -## Evidence rules - -### Task A +```mermaid +flowchart TD + A["Identify claim's
essential proposition"] --> B["Check same vote,
proposal, and actor"] + B --> C["Compare action, stance,
polarity, numbers, dates,
conditions, and scope"] + C --> D{"Source supports
claim?"} + D -->|Yes| E["Entailment"] + D -->|No| F{"Specific conflicting
source fact?"} + F -->|Yes| G["Contradiction"] + F -->|No| H["Neutral"] +``` -For entailment or contradiction, the model should return one to four -`{"page": integer, "text": string}` items copied from the supplied excerpts. -Neutral must return an empty array. After parsing, `build_evidence_a` verifies -the quote against the original PDF pages, returns the PDF's own text span, and -keeps the page number 1-based. It deduplicates matches and caps final evidence -at five items. +## API and recovery -If no quote matches but a non-neutral label requires evidence, the code uses a -page hint or word-overlap page and finally the first non-empty page. This is a -contract-preserving fallback, not proof that the model's quotation was correct. +- `LLMClient` in `src/llm_client.py` calls the OpenAI-compatible `chat.completions.create` endpoint with `temperature=0`, task-specific model settings, and JSON Schema output. +- Endpoint: `BASE_URL` (default `https://api.inference.cscs.ch/v1`); authentication uses `API_KEY` or its documented alias. +- Task B's prompt configuration sets `TASK_B_MAX_TOKENS = 100`. +- `MOCK_LLM=1` returns intentionally fake neutral responses for CI checks; it does **not** measure classification quality. +- A malformed response gets one correction attempt. The client separately retries transient API failures with bounded backoff. +- If processing still fails, `_fallback` emits a neutral prediction with empty evidence. This is an operational fallback, not a verified neutral judgment. -### Task B +## Evidence validation: keep these separate -The model must return `evidence: null`; the final contract uses `evidence: []`. -No citation mapping is performed because the reference text is already part of -the input and has no PDF page requirement. +1. **Schema validity** — response has the required JSON structure. +2. **Quote validity** — Task A quotation matches the original PDF. +3. **Evidence relevance** — the matched passage actually supports the predicted label. -## Difficult claims and error patterns +`build_evidence_a` verifies Task A quotes against original PDF text and preserves the source page. If a quote cannot be matched, fallback logic may use a hinted page, a word-overlap page, or the first non-empty page. This preserves output structure but **does not guarantee supporting evidence**. -The prompt and retrieval design specifically target claims where surface -similarity is misleading: +## Main failure modes the prompts target -| Claim pattern | Correct distinction | +| Risk | Prompt safeguard | |---|---| -| “The committee recommends rejecting the proposal.” vs. a source saying the proposal is unsuitable | Likely entailment if the source expresses the same stance; do not reverse the direction. | -| A claim attributes Parliament's position to the Federal Council | Neutral or contradiction depending on the source's explicit actor; shared topic is not enough. | -| “The measure reduces the tax by 20%” vs. a source giving a different percentage | Contradiction when the source clearly gives the incompatible figure. | -| “The proposal was accepted” vs. a booklet describing what would happen if accepted | Neutral: hypothetical consequences do not establish an acceptance result. | -| A claim adds an unsupported cause, date, scope, or certainty to an otherwise related statement | Neutral unless the source directly conflicts with that added detail. | -| A negated claim and a source with the opposite polarity | Entailment or contradiction must follow the actual polarity, not keyword overlap. | - -Common operational error patterns are missing/invalid JSON, unsupported model -evidence, wrong page hints, retrieval of a different proposal in the same -booklet, and overconfident contradiction when the source is merely silent. -`validate_output.py` catches structural violations, while evidence verification -and the evaluation script reveal weak citations and label errors. +| Missing detail treated as contradiction | Require a specific incompatible fact; otherwise prefer neutral | +| Keyword overlap mistaken for support | Check the central proposition and same vote | +| Actor or proposal confused | Verify attribution and proposal identity | +| Direction or negation reversed | Compare polarity and action direction | +| Hypothetical outcome treated as fact | Check conditions and whether the event actually occurred | +| Fabricated or irrelevant citations | Task A must quote supplied text verbatim and use the correct page | +| Explanatory prose breaks output format | Return JSON only | diff --git a/track_2a/docs/results.png b/track_2a/docs/results.png new file mode 100644 index 0000000..92069ac Binary files /dev/null and b/track_2a/docs/results.png differ diff --git a/track_2a/docs/retrieval.md b/track_2a/docs/retrieval.md index d902d21..c9e6398 100644 --- a/track_2a/docs/retrieval.md +++ b/track_2a/docs/retrieval.md @@ -1,55 +1,91 @@ -# PDF extraction and retrieval - -Task A retrieval is implemented in -[`src/pdf_loader.py`](../src/pdf_loader.py), -[`src/page_scoring.py`](../src/page_scoring.py), -[`src/sentence_splitter.py`](../src/sentence_splitter.py), -[`src/retrieval.py`](../src/retrieval.py), and -[`src/chunking.py`](../src/chunking.py). - -## PDF loading and cleaning - -[`load_pages`](../src/pdf_loader.py) opens a booklet with PyMuPDF and returns -one string per physical page. Extraction uses `page.get_text("blocks", -sort=True)` and orders blocks top-to-bottom, then left-to-right. This keeps -headings and columns more stable than treating the complete document as one -unstructured string. - -The `_clean` helper: - -- applies Unicode NFKC normalization; -- removes soft hyphens and converts non-breaking spaces; -- joins words split by a line-break hyphen; -- normalizes curly quotation marks; -- collapses horizontal whitespace; and -- joins wrapped lines inside paragraphs while preserving paragraph breaks. - -Page arrays are cached, and page numbers are always converted to human-facing -1-based numbers when sentence records or evidence are created. The original -page text is retained for evidence verification. - -## Page selection and sections - -Before sentence retrieval, [`select_relevant_pages`](../src/page_scoring.py) -scores every page against the case's vote title. Exact normalized title -matches score `100`; otherwise distinctive title words are weighted by -within-booklet IDF. Pages at or above `15` start relevant blocks, neighboring -pages at or above `5` are expanded, and one context page is added on each side. -The selected set is capped at `15` pages. If no page reaches the threshold, the -full booklet is retained. - -Section labels are optional metadata. The system first detects multilingual -contents pages in the first 12 physical pages, maps printed page numbers to -physical pages, and recognizes headings such as “In Kürze”, “En bref”, and “In -breve”. If that fails, recognized PDF bookmarks are used. - -## Sentence segmentation and chunks - -[`build_sentence_units`](../src/sentence_splitter.py) splits each page with -sentence-ending punctuation while protecting common abbreviations such as -`Dr.`, `Art.`, `z. B.`, `p. ex.`, and their multilingual equivalents. Each -record has a stable ID, 1-based page, optional section, source text, and -position: +# PDF Extraction and Retrieval + +## 1. Overview + +Task A retrieves supporting evidence from official Swiss federal voting booklet PDFs. The retrieval system converts each booklet into structured sentence-level records, identifies relevant pages, ranks candidate sentences using lexical and semantic similarity, and assembles a context that can be passed to the classification model. + +The retrieval pipeline combines **BM25 lexical retrieval** with **multilingual semantic retrieval**. Reciprocal Rank Fusion (RRF) merges both rankings so that the system can benefit from exact term matches and semantic similarity without relying on either ranking alone. + +The main stages are: + +1. Extract and clean text from the PDF. +2. Select relevant pages using the vote title. +3. Split page text into sentence-level records. +4. Rank sentences using lexical and semantic retrieval. +5. Fuse rankings and select candidate sentences. +6. Expand candidates with neighboring sentences and pack the context. +7. Map model-generated evidence back to the original PDF text. + +## 2. Retrieval architecture + +```mermaid +flowchart TD + A["Official voting
booklet PDF"] --> B["Extract and clean
page text"] + B --> C["Select relevant
pages"] + C --> D["Split into sentence
records"] + D --> E["BM25 lexical
ranking"] + D --> F["Multilingual embedding
ranking"] + E --> G["Reciprocal Rank
Fusion"] + F --> G + G --> H["Top 30 candidate
sentences"] + H --> I["Select top 15
candidates"] + I --> J["Expand neighboring
sentences"] + J --> K["Pack context within
character budget"] + K --> L["Classification
model"] + L --> M["Verify and map evidence
to source text"] +``` + +PDF extraction and sentence segmentation preserve page and source-position information throughout retrieval. This information allows the system to reconstruct readable context and associate evidence with its original page. + +## 3. PDF loading and text cleaning + +The `load_pages` function in `src/pdf_loader.py` uses PyMuPDF to extract one text string per physical PDF page. It reads text blocks using `page.get_text("blocks", sort=True)`, ordering them top-to-bottom and then left-to-right. This provides a more stable reading order than treating the complete document as one unstructured text string. + +The `_clean` helper applies the following transformations: + +- Unicode NFKC normalization. +- Removal of soft hyphens and conversion of non-breaking spaces. +- Joining of words split by line-break hyphenation. +- Normalization of curly quotation marks. +- Collapsing of horizontal whitespace. +- Joining of wrapped lines within paragraphs while preserving paragraph boundaries. + +Page arrays are cached to avoid repeated extraction. Physical PDF page indices are converted to human-facing, 1-based page numbers when creating sentence records and evidence. Original page text is retained for subsequent evidence verification. + +### Limitations + +Text extraction depends on the PDF's text layer and layout. Scanned pages without usable text, complex tables, multi-column layouts, and unusual reading orders may result in missing or incorrectly ordered text. The cleaning process can also incorrectly join words when a hyphen represents a genuine part of the original word. + +## 4. Relevant page selection + +Before sentence-level retrieval, `select_relevant_pages` in `src/page_scoring.py` scores every page against the case's voting title. + +The scoring procedure uses: + +- **Exact title matches:** normalized title matches receive a score of `100`. +- **Distinctive title words:** words are weighted using inverse document frequency (IDF) calculated within the booklet. +- **Relevant-page threshold:** pages scoring at least `15` can start relevant page blocks. +- **Neighbor expansion:** adjacent pages scoring at least `5` can expand those blocks. +- **Context expansion:** one additional page is included on either side of selected blocks. +- **Page cap:** the selected set is limited to `15` pages. + +If no page reaches the relevance threshold, the system retains the full booklet rather than returning an empty selection. + +This stage reduces the amount of text that must be segmented and ranked. However, it relies on the voting title being sufficiently representative of the wording used in the booklet. + +### Section metadata + +Section labels are optional metadata attached to sentence records. The system first attempts to detect multilingual table-of-contents pages within the first 12 physical pages. When successful, it maps printed page numbers to physical PDF pages and recognizes section headings such as “In Kürze”, “En bref”, and “In breve”. + +If table-of-contents processing fails, the system uses recognized PDF bookmarks as a fallback. Section metadata helps describe where evidence originates but is not itself a relevance score. + +## 5. Sentence segmentation and source records + +The `build_sentence_units` function in `src/sentence_splitter.py` splits each selected page into sentence-level records using sentence-ending punctuation. It protects common abbreviations, including `Dr.`, `Art.`, `z. B.`, `p. ex.`, and multilingual equivalents, to reduce incorrect sentence boundaries. + +Each sentence record contains a stable identifier, a physical page number, optional section metadata, the sentence text, and its position in the source sequence. + +Example: ```python { @@ -61,76 +97,162 @@ position: } ``` -[`pack_top_k_context`](../src/chunking.py) takes ranked sentences and expands -each by one neighboring sentence (`radius=1`) on the same page, without -crossing source-position gaps. Selected sentences are deduplicated by ID, -returned in original source order, and rendered with `[[PAGE n]]` and -`[Sxxxxx p.n]` markers. It accepts as much context as fits the -`MAX_INPUT_CHARS` budget, whose default is `600000`. - -## Lexical and semantic retrieval - -[`HybridRetriever`](../src/retrieval.py) uses two rankings: - -1. **Lexical:** a repository implementation of BM25 with `k1=1.5` and - `b=0.75`. Tokenization retains numbers, dates, punctuation-separated - numeric forms, and multilingual negation terms. -2. **Semantic:** `paraphrase-multilingual-MiniLM-L12-v2`, loaded from the local - model directory with `local_files_only=True` when available. Document and - query embeddings are encoded with `normalize_embeddings=True`, so vector - scores are cosine-like dot products. - -The embedding model is loaded lazily on the first retrieval request and -document embeddings are cached for that retriever. If a model path is not a -directory during local execution, the retriever downloads and saves the -configured multilingual model; Docker prevents this fallback with -`HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1`. - -## Merging, ranking, and limits - -Each ranking is converted to reciprocal-rank contributions with -`RRF_K=60`. The default lexical and semantic weights are both `1.0`. Results -are sorted by descending fused score, then original sentence order, and the -top `30` candidates are returned. - -The pipeline sends only the first `15` ranked candidates to context packing. -Neighbor expansion can add adjacent sentences, but the set of sentence IDs is -deduplicated before rendering. Context that would exceed the character budget -is skipped and `truncated` is recorded; the pipeline logs a warning. - -## Evidence mapping - -The model receives sentence IDs and page labels but must quote only source text. -After classification, [`PageIndex`](../src/evidence.py) squashes quotes and -page text to lowercase alphanumeric characters, making verification tolerant of -case, whitespace, punctuation, and PDF hyphenation differences. Matching -quotes are returned as spans from the original page text, with the hinted page -checked first. At most five evidence items are emitted, with a roughly 4,500 -character per-item limit. - -If a required non-neutral quote cannot be found, the evidence builder tries the -model's page hint, a best-overlap page, and finally the first non-empty page. -This preserves the output contract but may be weak evidence, so such fallbacks -should be inspected during evaluation. - -## Known failure modes and improvements - -The implementation has several predictable retrieval risks: - -- OCR errors, unusual reading order, multi-column layouts, tables, and - scanned/image-only PDFs can produce incomplete or misordered text. -- Sentence splitting is punctuation-based and may mishandle headings, - abbreviations not in its list, and language-specific typography. -- Vote-title page scoring can miss relevant pages when the title is abbreviated, - translated differently, or absent from the body; full-booklet fallback is - more expensive and noisier. -- BM25 can over-rank shared names, numbers, or vote terminology, while - embeddings can blur negation, actors, dates, and similar proposals. -- A small page cap and character budget can omit a decisive passage. -- Exact quote verification rejects paraphrases, even when the classification - itself is correct. - -Potential improvements include layout-aware extraction or OCR, language-aware -sentence segmentation, cross-encoder reranking, explicit negation/number -features, query expansion from vote metadata, adaptive page budgets, and -logging retrieval recall against gold evidence before changing thresholds. +The `position` field preserves the sentence's order within its source sequence. Sentence IDs support deduplication, retrieval ranking, context assembly, and evidence traceability. + +Sentence segmentation is punctuation-based rather than language-model-based. Unrecognized abbreviations, headings, lists, and language-specific typography can therefore produce incorrect boundaries. + +## 6. Hybrid lexical and semantic retrieval + +`HybridRetriever` in `src/retrieval.py` creates two independent rankings of the sentence records. Both rankings use the claim and associated case information as retrieval input. + +### 6.1 Lexical retrieval: BM25 + +The lexical retriever uses a repository implementation of BM25 with: + +- \(k_1 = 1.5\) +- \(b = 0.75\) + +BM25 rewards terms that are informative for a query while accounting for their frequency in a sentence and the length of that sentence relative to the collection. + +Tokenization preserves numbers, dates, punctuation-separated numeric forms, and multilingual negation terms. This is useful for voting booklets, where details such as dates, monetary amounts, named actors, and negation can determine whether a claim is supported or contradicted. + +Lexical retrieval can nevertheless over-rank sentences that share common vote terminology, names, or numbers without expressing the same proposition. + +### 6.2 Semantic retrieval: multilingual embeddings + +The semantic retriever uses `paraphrase-multilingual-MiniLM-L12-v2`, loaded from the local model directory. + +Document sentences and queries are encoded with `normalize_embeddings=True`. The resulting normalized vectors are compared using dot products, which behave like cosine similarity for normalized vectors. + +Semantic retrieval can identify relevant sentences when the claim and source use different wording or languages. However, semantic similarity does not guarantee logical entailment: sentences with similar topics may differ in negation, quantities, dates, or the actors involved. + +### 6.3 Model loading and caching + +The embedding model is loaded lazily when retrieval is first requested. Document embeddings are cached for the lifetime of the retriever to avoid recomputing them for repeated queries against the same sentence collection. + +During local execution, if the configured model path is not a directory, the retriever can download and save the configured multilingual model. Docker disables Hugging Face network fallback using: + +```text +HF_HUB_OFFLINE=1 +TRANSFORMERS_OFFLINE=1 +``` + +Consequently, the model must be present in the expected local directory before an offline Docker run. + +## 7. Ranking fusion and candidate selection + +Lexical and semantic rankings are merged using **Reciprocal Rank Fusion (RRF)**. Instead of combining raw BM25 scores and embedding similarities directly, RRF combines the rank positions assigned by each retrieval method. + +The fused score for a sentence is calculated as: + +```text +RRF(d) = Σ [w_r / (K + rank_r(d))] +``` + +Here: + +- `d` is the candidate sentence. +- `r` represents a retrieval ranking, either lexical or semantic. +- `w_r` is the weight assigned to that ranking. +- `rank_r(d)` is the position of sentence `d` in ranking `r`. +- `K` is the RRF constant, configured as `60`. + +The default ranking weights are: + +| Retrieval method | Weight | +|---|---:| +| Lexical (BM25) | `1.0` | +| Semantic (embeddings) | `1.0` | + +Each ranking contributes more to sentences appearing near its top. RRF combines these contributions, allowing a sentence to rank highly when it performs well in either or both retrieval methods. + +Candidates are sorted by descending fused score, with original sentence order used to break ties. The retriever returns the top `30` candidates, and the pipeline passes the first `15` to context packing. + +## 8. Context assembly and character limits + +The `pack_top_k_context` function in `src/chunking.py` turns ranked sentence candidates into readable source context. + +For each selected sentence, it expands the selection by one neighboring sentence on either side (`radius=1`). Expansion remains on the same page and does not cross gaps in source positions. + +The packing process: + +1. Selects the highest-ranked candidates supplied by the pipeline. +2. Adds eligible neighboring sentences. +3. Deduplicates sentences by ID. +4. Restores original source order. +5. Renders page and sentence markers. +6. Adds context while respecting the configured character budget. + +Rendered context uses markers such as: + +```text +[[PAGE 3]] +[S00001 p.3] Sentence from the voting booklet. +[S00002 p.3] Following sentence from the same page. +``` + +The default `MAX_INPUT_CHARS` budget is `600000`. Context that would exceed the budget is skipped, and the `truncated` state is recorded. The pipeline logs a warning when truncation occurs. + +Neighbor expansion provides local context that may be necessary to interpret a sentence correctly. However, expansion can add text that is less relevant to the claim, and a strict character budget can exclude a decisive passage. + +## 9. Evidence mapping and verification + +After classification, `PageIndex` in `src/evidence.py` maps model-generated evidence back to the original PDF text. + +The verification procedure normalizes quotes and page text by converting them to lowercase alphanumeric characters. This makes matching tolerant of differences in case, whitespace, punctuation, and PDF hyphenation. + +When a quote matches, the evidence builder returns a span from the original page text rather than relying solely on the model's reconstructed wording. A hinted page is checked first. + +At most five evidence items are emitted, with a roughly 4,500-character limit per item. + +### Evidence fallback behavior + +If a required non-neutral quote cannot be found, the evidence builder attempts the following fallbacks: + +1. Check the model's hinted page. +2. Find a page with the best overlap. +3. Use the first non-empty page as a final fallback. + +These fallbacks help preserve the expected output structure, but they do not guarantee that the resulting text supports the predicted label. Evidence generated through fallback paths should therefore be inspected during evaluation. A structurally valid prediction is not necessarily a semantically correct prediction. + +## 10. Main retrieval parameters + +| Parameter | Default | Purpose | +|---|---:|---| +| Exact title match score | `100` | Prioritizes pages containing the normalized vote title | +| Relevant-page threshold | `15` | Allows a page to start a selected block | +| Neighbor-page threshold | `5` | Allows adjacent pages to expand a block | +| Maximum selected pages | `15` | Limits page selection | +| BM25 \(k_1\) | `1.5` | Controls term-frequency saturation | +| BM25 \(b\) | `0.75` | Controls document-length normalization | +| RRF constant | `60` | Controls rank contribution decay | +| Lexical weight | `1.0` | Controls lexical ranking contribution | +| Semantic weight | `1.0` | Controls semantic ranking contribution | +| Retrieved candidates | `30` | Number of fused candidates returned | +| Candidates passed to packing | `15` | Initial context selection size | +| Neighbor radius | `1` | Number of neighboring sentences considered on each side | +| `MAX_INPUT_CHARS` | `600000` | Maximum packed context length | +| Maximum evidence items | `5` | Limits emitted evidence items | +| Evidence item character limit | About `4500` | Limits individual evidence length | + +These values describe the current configuration and should be changed only after evaluating their effects on retrieval quality, context size, runtime, and evidence validity. + +## 11. Known limitations and improvement opportunities + +The current retrieval design has several predictable failure modes. + +| Risk | Potential effect | Possible improvement | +|---|---|---| +| Scanned or poorly structured PDFs | Missing or misordered source text | OCR and layout-aware extraction | +| Incorrect sentence boundaries | Evidence split across records | Language-aware segmentation | +| Abbreviated or translated vote titles | Relevant pages missed | Query expansion using vote metadata | +| Full-booklet fallback | Higher retrieval cost and noisier candidates | Improve page-selection recall | +| Shared terms or numeric values | Irrelevant lexical matches | Add claim-specific numeric and negation features | +| Similar wording but different meaning | Semantically related yet incorrect evidence | Cross-encoder reranking and contradiction-aware features | +| Page and context caps | Decisive evidence omitted | Adaptive page selection and context budgets | +| Exact quote verification | Valid paraphrases rejected | Improve quote alignment while preserving source traceability | +| Evidence fallback | Weak evidence associated with a prediction | Record fallback usage and evaluate evidence quality separately | + +The most useful next step is to measure retrieval recall against known gold evidence before changing thresholds or ranking weights. This can show whether errors originate in PDF extraction, page selection, sentence retrieval, context packing, or the classifier itself. + +Retrieval quality and classification quality should be evaluated separately: a classifier cannot reliably use evidence that the retrieval stage never provides, while a highly ranked passage does not automatically establish entailment or contradiction. \ No newline at end of file diff --git a/track_2a/reports/fullsettest.json b/track_2a/reports/fullsettest.json new file mode 100644 index 0000000..a487b1e --- /dev/null +++ b/track_2a/reports/fullsettest.json @@ -0,0 +1,146 @@ +{ + "cases": 2976, + "responses": 2976, + "issues": {}, + "tasks": { + "A": { + "cases": 1488, + "macro_f1": 0.9274965675901674, + "threshold": 0.6, + "passes_threshold": true, + "accuracy": 0.9280913978494624, + "per_class": { + "entailment": { + "precision": 0.9533898305084746, + "recall": 0.9090909090909091, + "f1": 0.9307135470527405, + "support": 495 + }, + "neutral": { + "precision": 0.9003623188405797, + "recall": 0.9979919678714859, + "f1": 0.9466666666666667, + "support": 498 + }, + "contradiction": { + "precision": 0.9353448275862069, + "recall": 0.8767676767676768, + "f1": 0.9051094890510949, + "support": 495 + } + }, + "evidence_score": 0.7636363636363637, + "evidence": { + "cases": 990, + "found": 756, + "without_gold_passage": 0 + } + }, + "B": { + "cases": 1488, + "macro_f1": 0.9621752966673683, + "threshold": 0.7, + "passes_threshold": true, + "accuracy": 0.9623655913978495, + "per_class": { + "entailment": { + "precision": 0.9705882352941176, + "recall": 1.0, + "f1": 0.9850746268656716, + "support": 495 + }, + "neutral": { + "precision": 0.9616161616161616, + "recall": 0.9558232931726908, + "f1": 0.9587109768378651, + "support": 498 + }, + "contradiction": { + "precision": 0.9544513457556936, + "recall": 0.9313131313131313, + "f1": 0.9427402862985685, + "support": 495 + } + } + } + }, + "languages": { + "A de->de": { + "cases": 159, + "macro_f1": 0.9539982785884424 + }, + "A de->fr": { + "cases": 149, + "macro_f1": 0.8999509803921568 + }, + "A de->it": { + "cases": 147, + "macro_f1": 0.8584449496963101 + }, + "A fr->de": { + "cases": 184, + "macro_f1": 0.9235609533069425 + }, + "A fr->fr": { + "cases": 196, + "macro_f1": 0.9281537176274018 + }, + "A fr->it": { + "cases": 189, + "macro_f1": 0.9476894807407764 + }, + "A it->de": { + "cases": 152, + "macro_f1": 0.9218289318092235 + }, + "A it->fr": { + "cases": 152, + "macro_f1": 0.9518803104646661 + }, + "A it->it": { + "cases": 160, + "macro_f1": 0.9496188362115782 + }, + "B de->de": { + "cases": 159, + "macro_f1": 0.9469785575048731 + }, + "B de->fr": { + "cases": 149, + "macro_f1": 0.9398488013939007 + }, + "B de->it": { + "cases": 147, + "macro_f1": 0.9438918512441892 + }, + "B fr->de": { + "cases": 184, + "macro_f1": 0.9669135523756599 + }, + "B fr->fr": { + "cases": 196, + "macro_f1": 0.9789550340730165 + }, + "B fr->it": { + "cases": 189, + "macro_f1": 0.9582465207677192 + }, + "B it->de": { + "cases": 152, + "macro_f1": 0.9616897803760037 + }, + "B it->fr": { + "cases": 152, + "macro_f1": 0.9738767768842956 + }, + "B it->it": { + "cases": 160, + "macro_f1": 0.9807435254803676 + } + }, + "usage_mean_per_case": { + "input_tokens": 2978.8128360215055, + "output_tokens": 60.80745967741935, + "inference_time_ms": 2664.884744623656 + } +} diff --git a/track_2a/src/clean.py b/track_2a/src/clean.py deleted file mode 100644 index 1990419..0000000 --- a/track_2a/src/clean.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Runtime deduplication using input data.""" -import re -import unicodedata - - -def normalize(text): - if not isinstance(text, str): - return "" - text = unicodedata.normalize("NFKC", text) - text = text.replace("\u00ad", "") - return re.sub(r"\s+", " ", text).strip().casefold() - -def clean_cases(cases): - """Returns: (unique_cases, duplicate_ids)""" - seen = set() - unique_cases = [] - duplicate_ids = [] - for case in cases: - claim = case.get("claim", {}) - is_task_a = "booklet" in case - task = "A" if is_task_a else "B" - vote = normalize(case.get("vote", "")) - claim_text = normalize(claim.get("text", "")) - claim_language = normalize(claim.get("language", "")) - if is_task_a: - source = case.get("booklet", {}) - source_key = normalize(source.get("path", "")) - source_language = normalize(source.get("language", "")) - key = (task, vote, source_key, source_language, claim_language,claim_text) - else: - source = case.get("reference", {}) - source_text = normalize(source.get("text", "")) - source_language = normalize(source.get("language", "")) - key = (task, vote, source_language, source_text, claim_language, claim_text) - - if key in seen: - duplicate_ids.append(case.get("id")) - continue - seen.add(key) - unique_cases.append(case) - - return unique_cases, duplicate_ids diff --git a/track_2a/src/cli.py b/track_2a/src/cli.py index 64cdd36..22bb910 100644 --- a/track_2a/src/cli.py +++ b/track_2a/src/cli.py @@ -5,7 +5,6 @@ import sys from pathlib import Path -from .clean import clean_cases from .config import get_settings from .io_utils import read_cases from .llm_client import LLMClient @@ -35,11 +34,7 @@ def main(argv=None) -> int: log.info("Log file: %s", log_path) st = get_settings() cases = list(read_cases(a.input)) - original_count = len(cases) - cases, duplicate_ids = clean_cases(cases) - log.info("Input cases: %d | duplicates removed: %d | unique cases: %d",original_count,len(duplicate_ids),len(cases)) - if duplicate_ids: - log.warning("Duplicate case IDs skipped: %s", duplicate_ids) + log.info("Input cases: %d | processing all cases without deduplication", len(cases)) llm = LLMClient(st) Path(a.output).parent.mkdir(parents=True, exist_ok=True) done =0 diff --git a/track_2a/technical_report.md b/track_2a/technical_report.md index 5af3b69..e668038 100644 --- a/track_2a/technical_report.md +++ b/track_2a/technical_report.md @@ -1,63 +1,205 @@ -# Technical report — `project name` +# Technical Report — Multilingual NLI over Swiss Voting Booklets -A deeper write-up than the README: what you built, how it works, and what the -numbers say. Also check the specific submission requirements for your Academia -challenge and add required information here. - -- **Track:** `Track 2A — challenge name` -- **Event:** Online -- **Team:** `team name` — `member`, `member`, `member` -- **Demo:** `link to video, deployment, or notebook` +- **Track:** Track 2A — OST: Multilingual Natural Language Inference over Swiss Official Voting Booklets +- **Event:** HackApertus — Online +- **Team:** `OpenAlps` — `Rohita` +- **Repository:** `https://github.com/rohIta-k/OpenAlps` ## 1. Summary -The problem, your approach, and the headline result in one paragraph. +This project addresses multilingual Natural Language Inference (NLI) over Swiss official voting booklets. Given a claim and its associated source, the system determines whether the source **entails**, **contradicts**, or is **neutral** toward the claim. The challenge is not simply to classify text, but to identify reliable evidence in lengthy, structured documents containing multiple voting proposals and information across German, French, and Italian. + +The solution combines PDF text extraction, proposal-aware page selection, sentence-level processing, hybrid lexical and semantic retrieval, and Apertus v1.5 for structured classification. A separate evidence-verification stage checks model-generated quotations against the original source before predictions are written in the required JSONL format. The central engineering objective is to balance classification quality, evidence reliability, and inference efficiency while keeping the execution reproducible. ## 2. Architecture -Components, data flow, and where each one runs. Put diagrams in `docs/` and -reference them here. +The system follows a source-grounded pipeline in which document processing and retrieval prepare the context before Apertus performs the classification. + +```mermaid +flowchart TD + INPUT["Input cases
JSONL"] --> VALIDATE["Validate
input"] + VALIDATE --> ROUTER{"Source
type"} + + subgraph TASK_A["Task A
Voting booklet"] + PDF["Parse
PDF"] + PAGES["Select
relevant pages"] + SENTENCES["Process
sentences"] + RETRIEVAL["Hybrid retrieval
BM25 + dense"] + CONTEXT_A["Assemble
context"] + PDF --> PAGES --> SENTENCES --> RETRIEVAL --> CONTEXT_A + end + + subgraph TASK_B["Task B
Reference text"] + REFERENCE["Read direct
reference"] + CONTEXT_B["Prepare
context"] + REFERENCE --> CONTEXT_B + end + + ROUTER -->|Task A| PDF + ROUTER -->|Task B| REFERENCE + CONTEXT_A --> PROMPT["Build
task prompt"] + CONTEXT_B --> PROMPT + PROMPT --> API["Apertus v1.5
API"] + API --> PARSE["Parse and validate
NLI output"] + PARSE --> EVIDENCE["Verify
Task A evidence"] + EVIDENCE --> OUTPUT["Write prediction
JSONL"] + OUTPUT --> EVAL["Run official
evaluation"] +``` + +### Main components + +- **Input processing:** Reads cases from JSONL and distinguishes between booklet-based and reference-text cases. +- **Document processing:** Extracts page-level text from PDFs while preserving page information for evidence attribution. +- **Proposal selection:** Narrows the document to the relevant voting proposal before searching for supporting passages. +- **Retrieval:** Combines BM25 lexical retrieval with multilingual sentence embeddings. Reciprocal Rank Fusion combines their rankings. +- **Context assembly:** Selects relevant sentences and surrounding context while retaining source and page identifiers. +- **Classification:** Sends task-specific instructions and source context to Apertus v1.5. +- **Evidence verification:** Checks returned quotations against the original text and maps verified passages to their source pages. +- **Output and evaluation:** Produces structured predictions and evaluates them using the official Hackstarter evaluator. + +Task A requires PDF processing, retrieval, and page-grounded evidence. Task B uses its supplied reference text directly, avoiding unnecessary PDF processing and retrieval. + +The implementation is packaged in Docker for a consistent runtime environment. The embedding model is intended to be available locally within the image, while Apertus inference uses the configured API endpoint. + +For detailed implementation information, see [Architecture](docs/architecture.md), [Pipeline](docs/pipeline.md), [Retrieval](docs/retrieval.md), and [Classification](docs/classification.md). + ## 3. Use of Apertus -- **Model:** `e.g. swiss-ai/Apertus-v1.5-8B` -- **How it is used:** inference | fine-tuning | evaluation | red-teaming | agents / tool use -- **Where it runs:** `local weights, hosted endpoint, ...` +Apertus v1.5 was used as the main NLI classifier for both tasks, with the 70B model for Task A and the 8B model for Task B. Its multilingual capabilities helped us reason across claims and source documents written in different languages, even when they expressed the same information using different wording. +- **Models:** `swiss-ai/Apertus-v1.5-70B` (Task A) and `swiss-ai/Apertus-v1.5-8B` (Task B). +- **Inference:** Through the configured Apertus-compatible API. + +We experimented with how the context was presented to Apertus. Instead of relying only on isolated sentences, we included relevant surrounding text so the model could interpret statements in context and avoid missing relationships between a claim and the source. This was particularly useful when the meaning depended on surrounding explanations or qualifications. + +Prompt design was also important. We explicitly defined the three labels, clarified when missing information should be classified as neutral rather than contradiction, and set clear constraints on the expected response format and length. These refinements helped address inconsistent classifications and malformed outputs encountered during early iterations, while improving the model's ability to identify supporting evidence. + +The final approach combines relevant source context with task-specific prompting, allowing Apertus to perform the semantic comparison while the pipeline handles retrieval, output validation, and evidence checks. + +See [Classification](docs/classification.md) for implementation details. -Prompts, adapters, quantisation, serving stack — whatever a reader needs to -rebuild your setup. ## 4. Data -What you used, where it came from, and its licence. Flag anything personal or -non-redistributable, and keep it out of the repository (see `.gitignore`). -If data comes from human subjects or contains personal information, describe -how consent was obtained. +The development dataset is based on **`OSTswiss/MNLIoverSwissVotingBooklets`**, version `v1.1`, distributed under the MIT License. + +The dataset contains claims paired with reference text and associated voting-booklet information. The preparation pipeline deduplicates the source records and creates separate cases for the two task types: + +- **Task A:** Claim versus the corresponding official voting booklet. +- **Task B:** Claim versus the provided reference text. + +After deduplication, the prepared dataset contains 1,153 unique source rows, represented as 2,306 Task A and Task B cases. + +The data was divided into development, validation, and test pools using voting-day grouping, with a 40/30/30 split and seed `0`. Grouping by voting day helps prevent related cases from the same voting day from crossing evaluation pools. The committed split manifest records the resulting assignments. + +| Pool | Unique source rows | +|---|---:| +| Development | 458 | +| Validation | 372 | +| Test | 323 | +| **Total** | **1,153** | + +Only the intended sample data is committed to the repository. Additional downloaded datasets, custom inputs, and non-redistributable material should remain outside the committed sample unless their licensing permits redistribution. + +The input format supports relative booklet paths and language metadata. The source PDFs provide the evidence used by Task A, while Task B uses its reference text directly. + +See [Data documentation](docs/data/README.md) and the authoritative [split manifest](docs/splits.json) for data preparation and split details. ## 5. Evaluation -How you measured success: task, metric, baseline. +The primary evaluation objective is three-way classification across entailment, neutral, and contradiction. The main metric is **macro-F1**, which gives equal weight to each class rather than allowing performance on the most frequent class to dominate the result. + +Evaluation is performed using the official `evaluate.py` script provided in the Hackstarter repository. The same official evaluation procedure is used across experiments to maintain consistency. + +### Results + +| Metric | Baseline Task A (40 cases) | Baseline Task B (100 cases) | Final Task A (1,488 cases) | Final Task B (1,488 cases) | +|---|---:|---:|---:|---:| +| Macro-F1 | 0.8735 | 0.9577 | 0.9275 | 0.9622 | +| Accuracy | 0.9000 | 0.9600 | 0.9281 | 0.9624 | +| Evidence score | 0.4444 (12/27) | N/A | 0.7636 (756/990) | N/A | +| Mean input tokens/case | 28,141.95 | 2,065.05 | 2,978.81* | 2,978.81* | +| Mean output tokens/case | 108.03 | 14.28 | 60.81* | 60.81* | +| Mean inference time/case | 4,492.78 ms | 688.35 ms | 2,664.88 ms* | 2,664.88 ms* | +| Output-contract validation | Passed (40/40) | Passed (100/100) | Passed (2,976/2,976) | Passed (2,976/2,976) | -| Setup | Metric | Result | -|----------|--------|--------| -| Baseline | | | -| Ours | | | +\* Final-system token and inference-time values are overall averages across all 2,976 cases; task-specific averages were not provided. + +The final system improves Task A macro-F1 from 0.8735 to 0.9275 and Task B macro-F1 from 0.9577 to 0.9622. Task A evidence score increases from 0.4444 to 0.7636. + +The complete final evaluation results, including task-wise metrics, per-class performance, language-level scores, evidence scores, and token usage statistics, are available in [`reports/fullsettest.json`](reports/fullsettest.json). + +Individual experiment results, language-level metrics, and per-class comparisons are documented in the [`reports/`](reports/) folder. + +![Final evaluation results](../track_2a/docs/results.png) ## 6. Limitations -Where it breaks, what you did not test, and known failure modes. +- **Retrieval depth:** Retrieving too few sentences can miss important qualifications or supporting evidence. However, retrieving too many increases irrelevant context and can distract the classifier from the passage that actually determines the label. + +- **Context length:** Isolated sentences may lose the meaning of surrounding explanations, while excessively large contexts can introduce unrelated proposals, repeated information, or conflicting statements from different sections of a booklet. + +- **Proposal and page selection:** Narrowing retrieval to a specific proposal reduces noise, but an incorrect proposal match can exclude the relevant evidence entirely. Broadening the search helps recover missed passages but increases the risk of mixing information from different proposals. + +- **Lexical and dense retrieval balance:** Lexical retrieval is useful when claims share terminology with the source, but can miss semantically equivalent statements expressed in another language. Dense retrieval helps bridge this gap, although semantically similar passages are not necessarily evidence for the same claim. Relying too heavily on either method can therefore reduce retrieval quality. + +- **Classification prompt constraints:** Loose instructions can lead to inconsistent interpretations of entailment, neutral, and contradiction. Conversely, overly restrictive rules, lengthy prompts, or excessive output constraints can make the model miss valid evidence or produce incomplete responses. Prompt length and output limits must leave enough room for both the reasoning task and the required structured answer. + +- **Neutral versus contradiction:** Treating every unsupported claim as a contradiction increases false contradiction predictions. Being too conservative, however, can classify explicitly incompatible facts as neutral. The classifier must distinguish an absence of evidence from evidence that directly conflicts with the claim. + +- **Evidence extraction and verification:** Strict quotation matching improves traceability but may reject valid evidence because of PDF line breaks, hyphenation, or text extraction differences. More permissive matching can recover these cases, but risks accepting quotations that do not accurately correspond to the original source. + ## 7. Reproducibility -What a judge needs to get your numbers back: hardware, runtime, seeds, and the -exact commit. `make run` should do the rest. +The project uses a fixed dataset preparation procedure, a recorded split manifest, explicit model configuration, and a Docker-based runtime. -## 8. Next steps +A judge should: -What you would build with another month. +1. Clone the repository and enter `track_2a/`. +2. Install the required development dependencies using the documented setup. +3. Configure the Apertus API endpoint and API key. +4. Ensure the required embedding-model files are available before building the Docker image. +5. Build and run the solution using the documented Makefile targets. +6. Validate the generated predictions and run the official evaluation procedure. -## License +The evaluation container targets `linux/amd64`. Input data is mounted read-only at `/data`, predictions are written to `/output`, and temporary runtime files may use `/tmp`. The inference container should not require a runtime download of the embedding weights. + +Example commands, subject to the current Makefile configuration: + +```bash +cd track_2a + +# Install dependencies +uv sync + +# Run the solution on the default data directory +make run -Creative Commons Attribution 4.0 (CC-BY-4.0). All HackApertus projects are open-sourced. +# Validate predictions +uv run python scripts/validate_output.py \ + --cases data/cases.jsonl \ + --predictions output/predictions.jsonl +``` + +For custom data stored in a subdirectory, pass the corresponding `DATA` value to the Makefile target. The API key must be configured through the supported environment variables and must not be committed to the repository. + +Detailed installation instructions and runtime variables are documented in [Setup](docs/setup.md) and [Configuration](docs/configuration.md). + +## 8. Next Steps + +1. **Improve proposal selection:** Use table-of-contents entries, proposal titles, and page ranges to identify relevant sections more accurately and avoid retrieving evidence from unrelated proposals. + +2. **Analyze Task A errors:** Inspect evidence scores and retrieved passages for incorrect predictions, distinguishing cases where relevant evidence was missed from cases where Apertus received the correct context but predicted the wrong label. + +3. **Refine classification prompts:** Analyze label mismatches, especially neutral versus contradiction, to identify errors involving negation, numerical differences, actor attribution, or unsupported claims. + +4. **Optimize retrieval and context:** Experiment with retrieval depth, sentence selection, and context length to balance evidence coverage against irrelevant information. + +5. **Improve evidence handling:** Reduce quotation and page-reference errors using source-assigned sentence identifiers and more robust text matching. + +6. **Implement duplicate-input caching:** Cache inference results for identical inputs to avoid redundant model calls while preserving separate predictions for distinct case IDs. This can reduce inference time and token usage without compromising evaluation coverage. + +## License -## References +This project is released under the **Creative Commons Attribution 4.0 International (CC BY 4.0)** license, as specified by the HackApertus project requirements. Third-party datasets, models, and dependencies remain subject to their respective licenses and terms.