RAG & Retrieval

Fine Tuning a LLM to index Graph RAG

Building a private, domain-tuned entity extractor for finance, and how it compares to GPT-4.

Key takeaways

  • The post builds a private/custom LLM entity extractor for the finance domain, arguing that for regulated, privacy-sensitive domains a private LLM is needed to safeguard data, and that dataset quality and quantity matter more than raw model size — a smaller model on high-quality data can outperform a larger one on poorly curated data.
  • Dataset guidance: at least 500–1000 reports as a bare minimum with an ideal range of ~3,000–10,000 quality samples; the team curated over 2,500 samples from publicly available filings (Apple, Uber, Tesla initially), with preprocessing, standardization, annotation (often via GPT-4), deduplication, and validation (precision/recall/F1).
  • They evaluated instruct versions of Roberta, Bert-base-uncased-large, Gliner-base, Llama 3.2-3B, Llama 3.1-8B and Mistral-7B; only relevant SEC 10-K sections (Items 1, 1A, 3, 7, 8, 10, 11, 14) are extracted using LlmSherpa or the paid SEC API, then formatted into templates like ChatML/ShareGPT and fine-tuned with LoRA/QLoRA on hardware such as an NVIDIA 4060 Ti 16GB.
  • LLaMA 3.1-8B-Instruct was chosen as the optimal model — balanced 8B parameter count, strong handling of financial/legal language, and resource efficiency (fine-tunable/deployable via LoRA on a 4060 Ti 16GB, with inference feasible on high-end CPUs).
  • Versus GPT-4/GPT-4o on a financial-metrics extraction task, the post reports the fine-tuned model produced schema-compliant JSON without hallucinated entity types (GPT-4 hallucinated undefined types like "Earnings"; GPT-4o omitted years), ran faster (cited as nearly 2x GPT-4o and over 4x GPT-4) and cheaper, while acknowledging a disadvantage of low recall.
On this pagesections

    How to Build an entity Extractor for finance domain

    We discussed how to build a graph rag and explored deeply on the indexing pipeline in our previous blogs.

    1. A Gentle introduction to Graph RAG.
    2. Deep Dive into Indexing Pipeline – Graph RAG
    3. How does an Entity Extractor work ? Indexing Graph RAG
    4. Finetuning LLMs using Modal

    In this blog, we walk through the process of building an Extractor, which is a key piece in the Indexing Pipeline of a Graph RAG. The Extractor as discussed in the previous blog is a language model capable of extracting entities and relationships to build a Knowledge Graph (KG). We also went into detail about types of extractor, like Private and Public, and compared the merits and demerits of both.

    We take the message from the previous blog that anytime we have a regulated domain, with privacy being a key consideration, we typically need a Private LLM to safeguard the data. This blog serves as a step by step guide on how to implement your own custom LLM as an Extractor for extracting domain specific entities.

    High Level understanding of the Process

    Private LLM based Extractors are trained on either the Domain or specific use dataset generated by the organization, which closely matches with the expected data  post training. When fine-tuning a large language model (LLM), the quality and quantity of the dataset play a crucial role in determining the model’s generation capabilities.

    This is based on our Observation comparing the outputs of Llama-3b vs Llama-8b, Llama-70b. While model size provides the foundational architecture and potential capacity, it is the dataset that fills this capacity with knowledge and behavior.

    A smaller model fine-tuned on a high-quality, diverse dataset can often outperform a larger model trained on less curated data. Dataset quality ensures the model learns accurate, coherent, and meaningful patterns, while quantity provides the breadth and depth of examples needed to generalize effectively. Striking the right balance between these factors is more impactful than solely focusing on scaling the model size.

    Comparison Table

    This emphasizes the importance of investing in data curation and preprocessing over merely increasing model parameters. Now that we have established the order of significance of each of the factors affecting the final output of the Extractor. Let’s take a closer look at each component.

    We at Dataworkz, built a series of fine-tuned models on publicly available SEC 10k annual reports.

    For our model choice, we fine-tuned instruct versions of Roberta, Bert-base-uncased-large, Gliner-base, Llama3.2-3b, Llama3.1-8b and compared it to their base versions.

    Dataset Quality and why it matters

    Dataset quality directly affects the accuracy and coherence of the fine-tuned model. In the context of SEC 10-K reports, quality ensures the model understands financial terminologies, legal jargon, and the structural nuances of the reports.

    Best Practices and Rules of Thumb:

    • Preprocessing:
      • Convert PDFs into clean, structured text. Use tools like PyPDF2 or PDFPlumber to extract text while preserving formatting. Since this is a SEC document, we have tried both Llmsherpa and SEC Extractor API.
      • Handle OCR errors (if scanned PDFs) using libraries like Tesseract, LlmSherpa  and verify outputs against known samples.
      • Remove irrelevant sections, such as boilerplate disclaimers, to avoid diluting the training data.
    • Standardization:
      • Normalize company names, fiscal year formats, and monetary units for consistency.
      • Ensure dates, financial figures, and section headings follow a standard pattern.
    • Annotation:
      • Enrich the dataset with annotations such as entity labels (e.g., “Revenue”, “Net Income”, “CEO Name”) using tools like spaCy, Doccano or Argilla.
      • Focus on creating a taxonomy specific to financial entities and relationships.
    • Validation:
      • Manually review a subset of the data to ensure extraction accuracy.
      • If we have a labelled dataset, we can generate metrics like precision, recall and F1 score to compare the LLM extracted entities to the expected values.
      • Use domain experts to validate critical sections, such as MD&A (Management’s Discussion and Analysis).

    Dataset Quantity – How many samples do you actually need?

    A sufficient quantity of diverse examples ensures the model generalizes well across different companies and industries. However, excessive data may lead to diminishing returns or overfitting on repetitive patterns.

    Best Practices and Rules of Thumb:

    • Coverage:
      • Include reports from a wide range of industries (e.g., technology, healthcare, retail) to capture diverse terminologies and reporting styles.
      • Use recent 10-Ks to reflect contemporary language and financial standards.
    • Balanced Dataset:
      • Ensure representation of companies of varying sizes (e.g., Fortune 500, mid-cap, small-cap) to avoid bias.
      • Limit the dominance of specific industries to ensure general applicability.
    • Optimal Size:
      • Start with a minimum of 500–1000 reports for effective fine-tuning. Scale up incrementally while monitoring model performance.
      • If data scarcity exists, use synthetic augmentation (e.g., paraphrasing key sections) to expand the dataset.
    • Deduplication:
      • Remove duplicate or near-duplicate sections (e.g., standard risk disclosures) to prevent overemphasis on boilerplate language.

    We can conclude that we need at least 500 to 1000 samples at bare minimum, and the ideal range would be between 3000 to 10000 quality samples. We have curated over 2500 quality samples for the initial run, using publicly available data from Apple, Uber and Tesla. Though, on our later runs, we built a distributed dataset from various industries, which will be expanded on in the later sections.

    Model Size

    Model size determines the capacity to learn complex patterns but also comes with computational and memory constraints. For SEC 10-K reports, larger models may better capture intricate relationships but require substantial resources.

    Best Practices and Rules of Thumb:

    • Choose the Right Size:
      • For initial experiments, use models with 1–6 billion parameters (e.g., GPT-3’s smaller variants or LLaMA).
      • Scale up only if smaller models fail to capture nuanced financial reasoning.
    • Hardware Optimization:
      • Use an NVIDIA 4060 Ti 16GB GPU (or equivalent) with mixed-precision training to handle large models efficiently.
      • Leverage techniques like model parallelism or low-rank adaptation (LoRA) for resource-constrained environments.
    • Evaluate Trade-offs:
      • Balance the model’s size with fine-tuning objectives. For tasks like key entity extraction or section summarization, a moderately sized model suffices.
      • Larger models are ideal for generating detailed financial insights or complex Q&A.
    • Monitor Overfitting:
      • Watch for signs of overfitting, especially on repeated patterns in the reports. Use validation datasets to benchmark performance.

    Now that we got that out of the way, let’s talk about Dataset preparation and model selection.

    Dataset Preparation:

    The SEC Form 10-K is a company’s annual report that provides a comprehensive overview of its business and financial condition. It includes audited financial statements and other information, such as:

    • Board of directors: Whether each director is independent
    • Accounting fees: The fees paid to the company’s accounting firm for various services
    • Financial statements and exhibits: A list of the financial statements and exhibits included in the report, such as the company’s bylaws, contracts, and list of subsidiaries
    • Risk factors: A discussion of risks and uncertainties that could cause the company’s actual results to differ from those expressed in forward-looking statements

    We need to identify key parts of a SEC document, which might be of interest to us, in terms of relevancy of data. We also need to extract and  format only the required parts. After doing our research, we found out the relevant parts of a SEC annual report document:

    • Item 1: Business
    • Item 1A: Risk Factors
    • Item 3: Legal Proceedings
    • Item 7: Management’s Discussion and Analysis
    • Item 8: Financial Statements
    • Item 10: Directors, Executive Officers, and Governance
    • Item 11: Executive Compensation
    • Item 14: Principal Accountant Fees and Services

    Let’s extract only these sections

    To extract only the applicable parts, we need a PDF loader, which could skim through the document and give us layout wise access, so that we can isolate only the relevant information. For our use case, we have two PDF parsers:

    1. LlmSherpa
    2. SEC API (paid)

    We found that both these tools can be useful. We tried both of them to get section wise content extracted out.

    To create a high-quality dataset tailored for fine-tuning a large language model (LLM) on SEC 10-K reports, a structured and methodical approach is essential. The process involves several key steps to ensure the dataset is not only comprehensive but also aligned with the fine-tuning framework and objectives.

    Steps to Prepare and Fine-Tune the Dataset

    1. Structuring the Dataset for Fine-Tuning
      The dataset must be formatted into templates optimized for LLM consumption. Examples include formats such as:

      • ChatML: For multi-turn conversations or dialogues, often used in OpenAI models.
      • ShareGPT: For capturing detailed user interactions with assistant-style models.
    2. Fine-Tuning via Parameter-Efficient Techniques
      Fine-tuning leverages methodologies like:

      • LoRA (Low-Rank Adaptation): Enables efficient updates to model weights, focusing on domain-specific adjustments.
      • QLoRA (Quantized LoRA): Reduces memory requirements by fine-tuning on quantized models without significant loss in accuracy.
      • These approaches optimize for GPU efficiency, especially in resource-constrained environments, such as those using the NVIDIA 4060 Ti GPU.
    3. Evaluation, Testing, and Deployment
      Rigorous testing is necessary to evaluate the model’s ability to generate accurate and contextually relevant responses. Performance metrics like BLEU scores, ROUGE, and domain-specific accuracy can guide model deployment.

    Extracting and Preparing Relevant Content

    The foundation of a robust fine-tuning dataset lies in extracting the most pertinent sections from SEC 10-K reports. As identified, sections such as Item 1: Business, Item 7: Management’s Discussion and Analysis, and Item 8: Financial Statements are of high relevance.

    • Extractor Tools and Techniques
        • SEC API (Paid): A premium service designed for extracting structured and section-wise content directly from SEC filings. While this service provides reliable access to structured data, it requires a subscription and may incur costs.
        • LlmSherpa (Open Source):
          • A versatile document parsing tool integrated with frameworks like LlamaIndex and LangChain.
          • Capable of extracting both section-wise text and complex tabular data, such as consolidated financial statements.
    • Annotating the Dataset
        • Post-extraction, content can be annotated by domain experts to label entities, relationships, and sections accurately.
        • Alternatively, advanced LLMs (e.g., GPT-4) can assist in creating annotations programmatically. This is the method we picked to generate the dataset.
    • Incorporating Financial Tables
      • LlmSherpa allows us to get all the tables in the document, this is useful in our use case, as actual financial data usually is available as tables, which when passed with prompt can extract out all the relevant financial entities and relationships.

    By leveraging tools like LlmSherpa and SEC API, alongside advanced fine-tuning techniques such as LoRA, this methodology ensures the development of a domain-specific LLM capable of understanding and generating accurate insights from SEC 10-K reports. The combination of precise content extraction, annotation, and template structuring provides a solid foundation for downstream applications, such as financial summarization, risk analysis, and strategic decision-making.

    Prompt Engineering Guide

    Prompts guide the model to extract entities and relationships accurately. We have provided an example prompt tailored for SEC filings, we want it to extract all the entities which are extractable from the sections defined previously.

    Here’s an example tailored for SEC filings:

    You are an expert annotator of financial documents.

    You will be provided with a text chunk or table from an SEC 10-K Annual Report.

    Based on the Entity Types defined below, extract all relevant entities.

     

    Entity Types:

    – COMPANY_NAME

    – SUBSIDIARY

    – INDUSTRY

    – TICKER_SYMBOL

    – FISCAL_YEAR

    – RISK_FACTOR

    – LEGAL_PROCEEDINGS

    – NET_INCOME

    – REVENUE

    – LOSS

    – PROFIT

    ### Example output format:

    {examples}

     

    Document to Extract:

    {text}

     

    Return a JSON object with two keys entities and relationships. The response should only contain the JSON object and nothing else, ensuring it follows the example format given above.

     

    This structure ensures consistency and clarity when extracting entities across large datasets.

     

    The example output format could look like this:

    {

    “nodes”: [

    {

    “entity_type”: “COMPANY_NAME”,

    “entity_name”: “TechCorp Inc.”,

    “description”: “The main company filing the SEC 10-K report.”,

    “value”: null

    },

    {

    “entity_type”: “INDUSTRY”,

    “entity_name”: “Technology”,

    “description”: “The primary industry in which the company operates.”,

    “value”: null

    },

    {

    “entity_type”: “TICKER_SYMBOL”,

    “entity_name”: “TCRP”,

    “description”: “The stock ticker symbol for the company.”,

    “value”: null

    },

    {

    “entity_type”: “FISCAL_YEAR”,

    “entity_name”: “2023”,

    “description”: “The fiscal year covered in the 10-K report.”,

    “value”: null

    },

    {

    “entity_type”: “RISK_FACTOR”,

    “entity_name”: “Market Volatility”,

    “description”: “One of the risk factors identified in the report.”,

    “value”: null

    },

    {

    “entity_type”: “LEGAL_PROCEEDINGS”,

    “entity_name”: “Patent Dispute”,

    “description”: “A legal proceeding described in the document.”,

    “value”: null

    },

    {

    “entity_type”: “NET_INCOME”,

    “entity_name”: null,

    “description”: “Net income reported for the fiscal year.”,

    “value”: 35000000

    },

    {

    “entity_type”: “REVENUE”,

    “entity_name”: null,

    “description”: “Total revenue reported for the fiscal year.”,

    “value”: 500000000

    },

    {

    “entity_type”: “LOSS”,

    “entity_name”: null,

    “description”: “Reported losses, if any.”,

    “value”: 5000000

    },

    {

    “entity_type”: “PROFIT”,

    “entity_name”: null,

    “description”: “Reported profit after deducting all expenses.”,

    “value”: 34500000

    }

    ],

    “relationships”: [

    {

    “start_node”: “TechCorp Inc.”,

    “end_node”: “Technology”,

    “description”: “The company operates within this industry.”

    },

    {

    “start_node”: “TechCorp Inc.”,

    “end_node”: “TCRP”,

    “description”: “Ticker symbol for the company’s publicly traded shares.”

    },

    {

    “start_node”: “TechCorp Inc.”,

    “end_node”: “2023”,

    “description”: “The fiscal year covered in the report.”

    },

    {

    “start_node”: “TechCorp Inc.”,

    “end_node”: “Market Volatility”,

    “description”: “Identified as a key risk factor in the report.”

    },

    {

    “start_node”: “TechCorp Inc.”,

    “end_node”: “Patent Dispute”,

    “description”: “Ongoing legal proceedings involving the company.”

    },

    {

    “start_node”: “TechCorp Inc.”,

    “end_node”: “500000000”,

    “description”: “Total revenue generated in the fiscal year.”

    },

    {

    “start_node”: “500000000”,

    “end_node”: “35000000”,

    “description”: “Net income derived from the reported revenue.”

    },

    {

    “start_node”: “35000000”,

    “end_node”: “34500000”,

    “description”: “Net profit after accounting for all losses.”

    }

    ]

    }

    How to select the right Models

    The selection of the appropriate model is a critical step in fine-tuning, as it directly impacts the trade-offs between performance, computational requirements, and efficiency. For domain-specific tasks like processing and extracting insights from SEC 10-K reports, the ideal model must achieve a balance between high-quality results and resource efficiency, especially if the end-use scenario demands local inference on CPUs or modest GPUs.

    Factors Influencing Model Selection

    1. Model Size vs. Performance
      Larger models, such as LLaMA 3.1-13B, often yield superior generalization due to their higher parameter count. However, the gains may plateau for certain domain-specific tasks, making smaller, well-optimized models more practical.
    2. Domain Adaptability
      Models pretrained on diverse datasets with domain-agnostic capabilities (e.g., Mistral-7B) are highly versatile. However, domain-specific tasks benefit significantly from models that can be fine-tuned to understand niche terminologies, as seen in SEC filings.
    3. Hardware Constraints
      Lightweight models like LLaMA 3.2-3B-Instruct are designed to perform inference efficiently on consumer-grade hardware, making them suitable for scenarios with limited GPU or CPU resources.

    Model Options Evaluated

    • LLaMA 3.1-8B-Instruct
        • Why Chosen: This model strikes a balance between performance and resource efficiency. It is large enough to capture nuanced financial patterns in SEC 10-K filings while remaining computationally feasible for local inference.
        • Performance: Demonstrates high-quality output in summarization, entity extraction, and Q&A tasks.
        • Example Task: For the query, “What are the key risk factors for TechCorp Inc.?”, the model generates a coherent summary directly extracted from Item 1A.
    • Mistral-7B
        • Strengths: Noted for its high efficiency, particularly in inference tasks. Trained on diverse datasets, it handles both general-purpose and domain-specific applications reasonably well.
        • Example Task: Extracting numerical data (e.g., Net Income from Item 8: Financial Statements). The model performs well but may require additional fine-tuning for nuanced tasks like interpreting footnotes.
    • LLaMA 3.2-3B-Instruct
      • Strengths: Ideal for deployment in resource-constrained environments due to its small size. It achieves reasonable performance for straightforward tasks but may underperform on complex financial reasoning without extensive fine-tuning.
      • Example Task: Parsing basic entities such as Company Name or Fiscal Year from the text.

    Why was LLaMA 3.1-8B-Instruct Chosen

    • Balanced Parameter Count
        • At 8 billion parameters, it offers a middle ground between the efficiency of smaller models (e.g., 3B) and the depth of larger models (e.g., 13B).
    • Domain-Specific Precision
        • The model demonstrates an inherent ability to understand complex financial and legal language with minimal fine-tuning. For instance:
          • Input: Extract details from Item 3: Legal Proceedings.
          • Output: “TechCorp Inc. is involved in a patent dispute with Innovate LLC, with potential liabilities estimated at $2M.”
    • Resource Efficiency
        • The model can be fine-tuned and deployed on GPUs like the NVIDIA 4060 Ti 16GB using parameter-efficient methods such as LoRA, ensuring cost-effectiveness without compromising output quality.
        • For inference tasks, it operates smoothly on high-end CPUs, making it ideal for local deployments.
    • Customizability
      • Fine-tuning with PEFT methods enables customization for extracting structured data from tabular sections or generating summaries for specific sections like Management’s Discussion and Analysis (MD&A).

    Conclusion

    While all evaluated models offer unique strengths, LLaMA 3.1-8B-Instruct emerged as the optimal choice for SEC 10-K report processing. It combines robust performance in understanding domain-specific language with resource efficiency, making it well-suited for fine-tuning and deployment in financial analysis workflows. This decision aligns with the need for precision, adaptability, and cost-effective operation in real-world use cases.

    Let’s Finetune our Dataset

    Fine-tuning a large language model (LLM) involves customizing its capabilities to suit a specific task or domain by training it further on a prepared dataset. This process adapts the pre-trained model’s general knowledge to generate more accurate and contextually relevant outputs in a specific use case, such as processing SEC 10-K documents. The choice of platform and tools plays a significant role in ensuring the efficiency and effectiveness of this process.

    Platforms for Fine-Tuning

    • Cloud Platforms
        • Modal Labs
          Modal Labs simplifies deploying and scaling machine learning applications, including fine-tuning LLMs.

          • Infrastructure: Modal provides its own custom-built infrastructure, including a container runtime, file system, and scheduler, to optimize compute and storage.
          • Developer Experience: Its API-first approach allows developers to deploy scalable fine-tuning jobs using a few lines of Python code.
          • Pricing: Fully usage-based, making it cost-effective for teams with varying compute demands.
        • Anyscale
          Built around Ray, Anyscale allows users to fine-tune and deploy LLMs efficiently across distributed compute environments. Ideal for large-scale fine-tuning operations.
    • Local Fine-Tuning
      Tools like SFT-Trainer, PEFT, and Axolotl enable fine-tuning on personal hardware or local clusters, providing flexibility for smaller teams or budget-constrained projects.

    Tools for Fine-Tuning

    • SFT-Trainer (Supervised Fine-Tuning Trainer)
        • Purpose: Simplifies the process of supervised fine-tuning, where the model learns from input-output pairs.
        • Functionality: Automates dataset handling, tokenization, model checkpointing, and evaluation.
    • PEFT (Parameter-Efficient Fine-Tuning):
        • Purpose: Enables fine-tuning of large models with minimal computational overhead by adjusting a small subset of parameters.
        • Techniques: Includes methods like LoRA (Low-Rank Adaptation), QLoRA (Quantized LoRA), and prompt-tuning.
    • Axolotl:
      • Overview: A robust fine-tuning toolkit supporting a variety of model architectures and training configurations.
      • Features:
        • Supports Hugging Face models like LLaMA, Falcon, and GPT models.
        • Allows customization via YAML or CLI, enabling dynamic configuration of datasets, optimizers, and attention mechanisms.
        • Scales seamlessly from single GPU setups to multi-GPU clusters using FSDP or DeepSpeed.
      • Example: Fine-tuning Falcon-7B on SEC datasets using Axolotl’s QLoRA implementation and logging results to Weights & Biases for monitoring.

    How Fine-Tuning Works

    Fine-tuning adjusts a model’s internal parameters to align its outputs with the task-specific dataset, using supervised learning techniques.

    1. Pre-Trained Model as the Base:
      The LLM starts with pre-trained weights, where it has already learned general language representations from a large corpus (e.g., books, web text).
    2. Dataset Tokenization:
      Input data is tokenized into smaller chunks (tokens), allowing the model to process text in a structured way.

      • Example: “Revenue for 2023 is $500 million” becomes tokens like [Revenue], [2023], [is], [$500], [million].
    3. Forward Pass:
      Input tokens pass through the model’s layers. Each layer applies transformations to generate intermediate representations that capture the context of the input.
    4. Loss Calculation:
      The model’s output is compared to the target labels using a loss function (e.g., cross-entropy loss). The loss quantifies the error between the predicted and expected outputs.

      • Example: For a Q&A task, the model predicts an answer, which is compared against the ground truth answer.
    5. Backward Pass and Optimization:
      Gradients are calculated using backpropagation to determine how much each weight contributed to the error. These gradients are used by an optimizer (e.g., AdamW) to adjust the model’s weights, biases, and other trainable parameters.
    6. Layer Updates:
      • LoRA Example: Instead of updating all layers, LoRA introduces low-rank matrices that fine-tune only a subset of parameters, leaving the base model weights untouched.
      • Bias Updates: Fine-tuning might also focus on specific biases to minimize catastrophic forgetting of the pre-trained knowledge.
    7. Iterative Training:
      This process repeats over multiple epochs, progressively improving the model’s performance on the fine-tuning task.

    Click here for the step by step guide to Fine-tune using Modal-Labs.

    We also have our own guide, to fine-tune using modal.

    Evaluating the Performance of the Finetuned Model

    The performance of the fine-tuned LLM is evaluated against GPT-4 and GPT-4o using a financial metrics extraction task. The evaluation focuses on three key aspects: output accuracy, response quality, and response time. Below, we analyze how the models perform and highlight the significant advantages of the finetuned model over GPT-4 variants.

    Comparison of Outputs

    User Prompt (Truncated for readability):
    The task involves extracting structured financial metrics from a text snippet provided in SEC filings. The JSON schema is strictly defined, and only specific entity types are allowed.

    GPT-4o Output:
    • Extracted limited information, often missing crucial financial metrics.
    • Generated partial JSON, omitting key years (e.g., 2022, 2021).

     

    Output:

    {

    “entityType”: “Income”,

    “Type”: “Overall”,

    “Name”: “Net income”,

    “Year”: “2023”,

    “Total ($)”: “26,515”

    }

     

    GPT-4 Output (Temperature = 0.7):
    • Extracted more comprehensive data compared to GPT-4o.
    • Included metrics from all years but hallucinated additional, undefined entity types (e.g., “Earnings”), violating the prompt’s schema.

    Example of hallucinated entities:

    {

    “entityType”: “Earnings”,

    “Type”: “Overall”,

    “Name”: “Earnings per common share”,

    “Year”: “2023”,

    “Total (Optional Unit)”: “$ 3.10”

    }

     

    GPT-4 (Temperature = 0):
    • Improved compliance with the schema by reducing hallucinations.
    • However, some field names still deviated from the schema, and unnecessary attributes were retained.

    Finetuned LLM Output:

    • Delivered precise and schema-compliant JSON.
    • Accurately extracted required entity types without hallucination.

    Simplified output by removing unnecessary optional fields:

    [

    {

    “entityType”: “Income”,

    “Type”: “Overall”,

    “Name”: “Net income applicable to common shareholders”,

    “Year”: “2023”,

    “Total”: “$24,866 million”

    },

    {

    “entityType”: “Income”,

    “Type”: “Overall”,

    “Name”: “Net income applicable to common shareholders”,

    “Year”: “2022”,

    “Total”: “$26,015 million”

    },

    {

    “entityType”: “Income”,

    “Type”: “Overall”,

    “Name”: “Net income applicable to common shareholders”,

    “Year”: “2021”,

    “Total”: “$30,557 million”

    }

    ]

    Key Advantages of the Finetuned Model

    1. Schema Adherence:
      The finetuned model followed the prompt’s JSON schema strictly, avoiding any hallucinated entity types (e.g., “Earnings” or incorrect mappings like “Assets” for equity-related data).
    2. Noise Reduction:
      Unlike GPT-4, the fine-tuned model eliminated redundant attributes like “Optional Unit” and avoided including irrelevant entities.
    3. Response Consistency:
      • Maintained consistent formatting across entries.
      • Extracted only relevant metrics as per the schema without errors or oversights.
    4. Performance on Domain-Specific Tasks:
      The fine-tuned model outperformed GPT-4 in handling the nuanced domain requirements of SEC financial filings.

    Key Disadvantages of our Finetuned Model

    1. Low Recall: Recall is defined as the proportion of correctly identified entities corresponding to the total number of actual positive entities.

    Response Time Comparison

    The finetuned model demonstrated significantly faster response times, even when compared to GPT-4o, which is a distilled version of GPT-4:

    In the table above FT stands for Fine-Tuned. We tested both a commercial hardware (A100 GPU) and an entry level GPU (Nvidia RTX 4060ti). The inference speed depends on the CUDA cores and memory bandwidth and memory bus width and is also aided by vLLM and a quantized model.

     

    Hence, a stark contrast is observed between running the same finetuned model on a commercial vs a consumer GPU.

     

    Based on this, a chunk with 512 tokens would need less than 6s to be processed using a consumer gpu and approximately 1.7s with a commercial grade instance.

     

    We built a framework to calculate the average number of tokens in a SEC 10k annual report. We took a small sample set of 15 SEC documents of top companies in each of the relevant domains, like Tech, Finance, Pharma, Oil, Gas, Banking, etc. and estimated that on an average a SEC 10k Annual report has around 135k tokens.

    Now that we understand the response timings, let’s move on to cost comparison between our fine-tuned models and the GPT models.

    Cost Comparison

    On average a single SEC document has 135k tokens. Based on our estimates in our previous section, we can quickly realise the scale of this.

    When considering fine-tuning and deploying language models like LLaMA 3.2-3b and comparing them to GPT-4 and GPT-4O, performance metrics such as token processing speed, throughput, and cost of serving requests are key considerations. Here’s a detailed breakdown of the computational capabilities and implications for LLaMA 3.2-3b:

    Token Processing Speed

    The speed of processing tokens significantly impacts the overall throughput and, subsequently, the cost of deployment. For LLaMA 3.2-3b, the token processing speeds are:

    • Consumer-Grade Hardware: ~65 tokens/sec
    • Commercial-Grade Hardware: ~200.5 tokens/sec

    Performance Analysis on Commercial-Grade Hardware

    Commercial-grade hardware provides a significant speed advantage, enabling faster processing and greater throughput. For instance:

    1. Time Per Token: At 200.5 tokens/sec, each token takes approximately 1/200.5​ seconds. We tracked down the expected input and output tokens for NER extraction, and took the average numbers. We identified that each batch or chunk has around:
    1. 921.37 input tokens (452 system prompt + 469.37 user prompt)
    2. 327.22 output tokens
    1. Batch Processing:
      • A batch of 327.22 tokens (output) takes approximately 1.632 seconds for processing, with an additional 0.07 seconds for input overhead.
      • Total Time Per Batch: 1.702 seconds.
    2. Token Throughput:
      • A single input batch contains an average of 921.37 tokens.
      • In one second, we can process approximately:
        • 541.345 input tokens (These are just extrapolated values, in real setting we would be ideally passing the entire input tokens)
        • 192.482 output tokens

    Hourly and Daily Token CapacityGiven the above processing speeds, we can extrapolate the throughput for larger time scales:

    • Per Hour:
      • Input tokens processed: 1,948,842 tokens
      • Output tokens generated: 692,936 tokens
    • Per Day (24 Hours):
      • Input tokens processed: 46,772,249 tokens
      • Output tokens generated: 16,630,475 tokens

    Scaling with Concurrent Requests

    Scaling the system to handle concurrent requests dramatically increases the throughput. For example, with 3 concurrent requests:

    • Daily capacity increases to:
      • Input Tokens: 140,316,747 tokens
      • Output Tokens: 49,891,426 tokens

    Implications for Cost and Deployment

    1. Efficiency: The high token throughput on commercial-grade hardware makes LLaMA 3.2-3b highly efficient for large-scale deployments, especially when handling concurrent requests.
    2. Cost Savings: While the initial cost of fine-tuning and deploying LLaMA may be substantial, its operational efficiency can lead to lower per-token costs compared to API-based solutions like GPT-4.
    3. Customization: Fine-tuning allows for task-specific optimization, potentially improving performance on specific domains over general-purpose models like GPT-4 or GPT-4O.

    Let’s compare the realistic expectations from a single machine running our fine-tuned model to making API calls to OpenAI for the same set of input documents. We observe that a single Nvidia A100 40GB GPU machine from Modal costs us $2.78 /h (for the GPU).

    We can spawn a multithread process over the Ollama service, or directly use the HuggingFace to load our fine-tuned model. It can spawn up to 3 parallel instances, given that Llama3.1-8b-Instruct requires 12GB to operate.

    Let’s calculate the cost of running a GPU instance for 24 hours, and compare them to processing the equivalent number of tokens within the same time for GPT-4o, GPT-4 and GPT-4-Turbo.

    Renting a Nvidia A100 GPU with modal costs us around $ 3.299/hr. We would ideally like to run the machine around the clock, and track the tokens usage in a day, and extrapolate from processing the same no of tokens using gpt-4, gpt-4o and other paid models. Based on our observations earlier, in a single day, we are capable of handling 46.7M input tokens and 16.63M output tokens on a single thread.

     

    Model Input tokens cost (per million tokens) Output token cost (per million tokens) Total price (per day) in USD
    Gpt-4o $2.50 $10 283
    Gpt-4 $30 $60 2401
    Gpt-4-Turbo $10 $30 967
    llama3.2-3b NA NA 79.17

     

    The final cost is on demand pricing, reserved pricing brings it down to $55.4 rent per day. This is an approximate representation of the benefits of using a finetuned model vs gpt models (or) any other public models. We have taken realistic values for comparison, based on response time from each llm, and how many documents could be processed based on these numbers per day.

    Summary of Key Insights

    • Accuracy: The finetuned model surpassed GPT-4 in accuracy by adhering to the schema and domain requirements, avoiding hallucinations, and focusing on essential entities.
    • Speed: It was nearly twice as fast as GPT-4o and over four times faster than GPT-4, making it a practical choice for real-world applications.
    • Domain Customization: Tailoring the model through fine-tuning allowed it to better understand financial jargon, schema constraints, and the specific nuances of SEC filings.

    These results highlight the fine-tuned model’s capability as a lightweight, efficient alternative to GPT-4 for extracting domain-specific entities in a production environment.

    Wrapping Up

    By extracting domain-specific entities, you transform raw text into structured knowledge, enabling the construction of a rich and insightful knowledge graph. This graph not only enhances querying but also lays the groundwork for building intelligent and scalable enterprise systems like GraphRAG.

    Stay tuned for more insights on fine-tuning LLMs and integrating advanced graph-based solutions in enterprise applications!

    Frequently asked questions

    Why fine-tune a private LLM as an entity extractor instead of using a public LLM?

    The post argues that in regulated domains where privacy is a key consideration, a private LLM is typically needed to safeguard the data. A custom model is trained on the organization's domain-specific dataset so it closely matches the expected data, and the post found a well-fine-tuned smaller model can outperform a larger model trained on less curated data.

    How much data is needed to fine-tune an extractor for SEC 10-K reports?

    The post recommends a bare minimum of 500–1,000 reports and an ideal range of roughly 3,000–10,000 quality samples. It also stresses coverage across industries and company sizes, deduplication of boilerplate, and validation. The team curated over 2,500 samples for an initial run using publicly available filings from companies including Apple, Uber, and Tesla.

    Which model did the post choose and why?

    The post selected LLaMA 3.1-8B-Instruct as the optimal choice. At 8 billion parameters it balances the efficiency of smaller models (e.g., 3B) with the depth of larger ones, understands complex financial and legal language with minimal fine-tuning, and is resource-efficient enough to fine-tune and deploy via LoRA on an NVIDIA 4060 Ti 16GB, with inference feasible on high-end CPUs.

    How did the fine-tuned model compare to GPT-4 and GPT-4o?

    On a financial-metrics extraction task, the post reports the fine-tuned model produced precise, schema-compliant JSON without hallucinated entity types, whereas GPT-4o missed key years and GPT-4 hallucinated undefined types such as "Earnings." The post cites the fine-tuned model as nearly twice as fast as GPT-4o and over four times faster than GPT-4, and more cost-effective at scale. It notes a key disadvantage of low recall.

    What tools and techniques are used to prepare the dataset?

    The post uses PDF/section parsers (LlmSherpa, open source; or the paid SEC API) to extract only relevant 10-K sections (such as Item 1 Business, Item 7 MD&A, Item 8 Financial Statements, including tables), annotates the data via domain experts or an advanced LLM like GPT-4, structures it into templates such as ChatML or ShareGPT, and fine-tunes using parameter-efficient methods LoRA and QLoRA.

    See what your engineers can ship in production

    Dataworkz is the agentic AI platform enterprises trust to put AI agents into production. Teams build production-ready agents in days, every decision stays traceable, and every agent has ROI attached.

    Explore the platform