Knowledge Graph-Enhanced Machine Translation: Improving AI Translation with Context

translation xl- my dutch pal

I have recently been investigating how I can use RAG to improve the accuracy of LLM-based machine translation. In this article, I will take Knowledge Graphs as an advanced form of RAG and demonstrate how combining knowledge graphs with large language models can significantly improve machine translation accuracy, particularly for domain-specific content.. The article basically provides a “toy example” of the use of a Knowledge Graph to generate a translation of a short French text. The working Python code given below has been generated by Claude.ai.

The Challenge

Traditional machine translation systems often struggle with:

  • Domain-specific terminology
  • Proper nouns and entity names
  • Context-dependent translations
  • Technical jargon

The Solution: Knowledge Graph + LLM

By integrating a knowledge graph that stores entities and their relationships, we can provide contextual information to the translation model, resulting in more accurate and contextually appropriate translations.

Implementation

Here’s a complete implementation of a knowledge graph-enhanced French-to-English translator using Python and Ollama:

Knowledge Graph Class

class KnowledgeGraph:
    """Simple knowledge graph for storing entities and relationships"""
    
    def __init__(self):
        self.entities = {}
        self.relationships = []
    
    def add_entity(self, entity_id: str, entity_type: str, properties: Dict):
        """Add an entity to the knowledge graph"""
        self.entities[entity_id] = {
            'type': entity_type,
            'properties': properties
        }
    
    def add_relationship(self, source: str, relation: str, target: str):
        """Add a relationship between entities"""
        self.relationships.append({
            'source': source,
            'relation': relation,
            'target': target
        })
    
    def get_entity_context(self, entity_id: str) -> str:
        """Get contextual information about an entity"""
        if entity_id not in self.entities:
            return ""
        
        entity = self.entities[entity_id]
        context = f"{entity_id} is a {entity['type']}"
        
        # Add properties
        for key, value in entity['properties'].items():
            context += f", {key}: {value}"
        
        # Add relationships
        related = [r for r in self.relationships if r['source'] == entity_id]
        if related:
            context += ". Related to: "
            context += ", ".join([f"{r['target']} ({r['relation']})" for r in related])
        
        return context
    
    def find_entities_in_text(self, text: str) -> List[str]:
        """Find entities mentioned in text (simple string matching)"""
        found = []
        text_lower = text.lower()
        for entity_id in self.entities.keys():
            if entity_id.lower() in text_lower:
                found.append(entity_id)
        return found 

Enhanced Translator Class

class KGEnhancedTranslator:
    """Translator that uses knowledge graph context"""
    
    def __init__(self, model_name: str = "gemma2:2b"):
        self.model_name = model_name
        self.kg = KnowledgeGraph()
    
    def add_domain_knowledge(self, entities: List[Dict], relationships: List[Dict]):
        """Populate the knowledge graph with domain knowledge"""
        for entity in entities:
            self.kg.add_entity(
                entity['id'],
                entity['type'],
                entity['properties']
            )
        
        for rel in relationships:
            self.kg.add_relationship(
                rel['source'],
                rel['relation'],
                rel['target']
            )
    
    def translate(self, french_text: str) -> Dict[str, str]:
        """Translate French text to English using KG context"""
        
        # Find relevant entities in the text
        relevant_entities = self.kg.find_entities_in_text(french_text)
        
        # Build context from knowledge graph
        kg_context = ""
        if relevant_entities:
            kg_context = "Context information:\n"
            for entity in relevant_entities:
                kg_context += f"- {self.kg.get_entity_context(entity)}\n"
        
        # Create prompt with KG context
        prompt = f"""You are a French to English translator. Use the provided context to ensure accurate translation of domain-specific terms and proper nouns.

{kg_context}

Translate the following French text to English. Maintain the original meaning and use appropriate technical terminology based on the context provided.

French text: {french_text}

English translation:"""
        
        # Call Ollama
        response = ollama.chat(
            model=self.model_name,
            messages=[{
                'role': 'user',
                'content': prompt
            }]
        )
        
        return {
            'original': french_text,
            'translation': response['message']['content'].strip(),
            'context_used': kg_context,
            'entities_found': relevant_entities
        } 

Example Usage

import ollama
from typing import Dict, List

def main():
    """Example usage of KG-enhanced translation"""
    
    # Initialize translator
    translator = KGEnhancedTranslator(model_name="gemma2:2b")
    
    # Add domain knowledge about a fictional tech company
    entities = [
        {
            'id': 'TechCorp',
            'type': 'company',
            'properties': {
                'industry': 'technology',
                'headquarters': 'Paris',
                'founded': '2010'
            }
        },
        {
            'id': 'Marie Dubois',
            'type': 'person',
            'properties': {
                'role': 'CEO',
                'nationality': 'French'
            }
        },
        {
            'id': 'QuantumCore',
            'type': 'product',
            'properties': {
                'type': 'quantum processor',
                'release_year': '2024'
            }
        }
    ]
    
    relationships = [
        {'source': 'Marie Dubois', 'relation': 'works_at', 'target': 'TechCorp'},
        {'source': 'Marie Dubois', 'relation': 'leads', 'target': 'TechCorp'},
        {'source': 'TechCorp', 'relation': 'produces', 'target': 'QuantumCore'}
    ]
    
    translator.add_domain_knowledge(entities, relationships)
    
    # Example French texts to translate
    test_texts = [
        "Marie Dubois a annoncé que TechCorp lancera QuantumCore le mois prochain.",
        "Le nouveau processeur quantique révolutionnera l'informatique.",
        "TechCorp est basé à Paris et emploie plus de 500 personnes."
    ]
    
    for i, text in enumerate(test_texts, 1):
        print(f"\n--- Example {i} ---")
        result = translator.translate(text)
        
        print(f"\nOriginal (FR): {result['original']}")
        print(f"\nTranslation (EN): {result['translation']}")
        
        if result['entities_found']:
            print(f"\nEntities detected: {', '.join(result['entities_found'])}")
            print(f"\nContext used:\n{result['context_used']}")
        else:
            print("\nNo entities detected")

if __name__ == "__main__":
    main() 

Key Benefits

Contextual Accuracy: The system understands domain-specific entities and their relationships

Proper Noun Handling: Names and technical terms are translated appropriately

Scalable: Easy to extend the knowledge graph with new entities and relationships

Transparent: The system shows which entities were detected and what context was used

Use Cases

This approach is particularly valuable for:

  • Technical documentation translation
  • Business communications with specific terminology
  • Academic papers with domain-specific concepts
  • News articles about known entities and organizations

Next Steps

To extend this system, consider:

  • Implementing more sophisticated entity recognition (NER)
  • Adding support for additional languages
  • Integrating with enterprise knowledge bases
  • Implementing caching for frequently translated entities

Dependencies: ollama, Python 3.7+

The complete code is available and ready to use. Feel free to adapt it for your specific translation needs!

For more extensive use of this approach, I can be reached at support@localai.world.

#MachineLearning #NLP #AI #Translation #KnowledgeGraphs #Python

Essential RAG for translation

Does any LLM know everything about everything? Let’s face it – if a model hasn’t seen a term used in a certain specialised context in the training data it’s hardly likely to come up with a correct translation. Let’s take the Dutch word “heuvel”. If you’ve done the Duolingo Dutch course you’ll probably know that “heuvel” means “hill”, and the Dutch word for “hills” is “heuvelen”. But Duolingo won’t teach you that “heuvelen” also means “hump shunting”. Now, you may not know what “hump shunting” is, but I know as I spent many years translating railway engineering documents. What about ChatGPT? Does it know the meaning of “heuvelen”? Well, it tells us that “heuvelen” means “to form into hills”. Doesn’t quite fit in the railway engineering context, does it?

Getting the right translation of specialised terms has always been a challenge for translators. My younger self used to travel 60-odd miles on the train to London to visit specialist libraries in search of the right terminology. In Neural Machine Translation fine-tuning has proved to be to be the most effective way of getting a model to use correct terminology as the model learns context, and fine-tuning LLMs is certainly a viable way of injecting specialist knowledge into an LLM trained on general data. But is fine-tuning a practical solution for a user when faced with an urgent translation task in a highly specialised field on which their chosen LLM has probably not been trained? When reliable glossaries are available in digital format, Retrieval Augmented Generation (RAG) can be an effective tool for feeding an LLM with specialist terminology to be used in a translation task.

The Local AI Translator includes a “RAG Manager” which provides a process for taking glossaries and files to be translated and building a single glossary which covers all the documents for translation. This filtering capability is useful since it is unnecessary to extract, for example, all the terms related to the “railway universe” to translate a series of studies on the best design for automated level crossings. I have experimented with embeddings in educational software and our Local AI Legal Assistant relies on ChromaDB to analyze legal documents, but for technical translation I prefer to use a glossary based on verified pairs of terms and phrases or even the entries in a translation memory. The process shown in the attached video clip produces “prompt_data.json” This file is then loaded in the “load glossary” function to produce the following prompt:

prompt = f””” You are a translation assistant. Use the following glossary to translate specific terms in the provided text from {source_lang} to {target_lang}. Replace each term or phrase in the text with its corresponding translation from the glossary, preserving the sentence structure. If a term or phrase is not in the glossary, translate it using your internal resources. Do not provide explanations or comment on the translation. Glossary (JSON format): {glossary_str}”.

Sticking to the railway engineering field, an example of a Dutch-English glossary submitted to an LLM within a prompt is:

{“glossary”: {

“groepsrailrem”: “group retarder”,

“heuvel”: “hump”,

“heuvelloc”: “humping locomotive”,

“heuvellocomotieven”: “humping locomotives”,

“heuvelproces”: “hump shunting process”,

“heuvelprocesleider”: “hump yard master”,

“heuvelsysteem”: “hump shunting system”,

“heuveltop”: “crest of the hump”,

“hoofdrailrem”: “main retarder”, …

With most LLMs I have tested, it is sufficient to include the glossary in this format within the translation prompt as a {custom_prompt} for the model to know what to do, i.e. apply the terminology in the translation.

I am aware that this is a simplistic approach, an example of naive RAG. As I have mentioned above I used an embeddings based approach for the Local AI Legal Assistant which can perform analysis of complex legal documents. However, the purpose of the Local AI Translator is to provide a tool for generating LLM-based translations offline on relatively low-cost entry-level computers which would not be powerful enough to run applications like ChromaDB without serious latency issues.

This essential RAG function is offered to the users of the Local AI Translator as a straightfoward approach for ensuring greater terminological accuracy in their machine translations.

For more information on the Local AI Translator visit https://localai.world. For the video clip on Essential RAG for Translation, see
https://www.youtube.com/watch?v=S0ZzRPcm1Ts&ab_channel=LocalAIWorld

Background information of the Local AI Medical Assistant

The Local AI Medical Assistant is basically a frontend to Google Health’s MedGemma model. This post aims to provide some background information on this healthcare model.  In the interests of transparency we include references to the model’s limitations.

The information contained in this post has been taken  from MedGemma/README.md at main · Google-Health/MedGemma · GitHub.  While the model is licensed under the Health AI Developer Foundations License, everything in MedGemma repository is licensed under the Apache 2.0 license. In the Local AI Medical Assistant the model runs within the Ollama framework.

MedGemma

MedGemma is a collection of Gemma 3 variants that are trained for performance on medical text and image comprehension. Developers can use MedGemma to accelerate building healthcare-based AI applications. MedGemma comes in two variants: a 4B multimodal version and a 27B text-only version. The Local AI Medical Assistant utilizes the 4B multimodal version which allows  both text and image input.

MedGemma 4B utilizes a SigLIP image encoder that has been specifically pre-trained on a variety of de-identified medical data, including chest X-rays, dermatology images, ophthalmology images, and histopathology slides. Its LLM component is trained on a diverse set of medical data, including radiology images, histopathology patches, ophthalmology images, dermatology images, and medical text.

MedGemma variants have been evaluated on a range of clinically relevant benchmarks to illustrate their baseline performance. These include both open benchmark datasets and curated datasets, with a focus on expert human evaluations for tasks.

The following sections present some common use cases for the model. You’re free to pursue any use case, as long as it adheres to the Health AI Developer Foundations terms of use.

Medical image interpretation

MedGemma’s pre-trained multimodal variants are well-suited for tasks like generating medical image reports or answering natural language questions about medical images. While its baseline performance is strong compared to similar models, MedGemma isn’t yet clinical-grade and will likely require further fine-tuning.

Medical text comprehension and clinical reasoning

MedGemma can be adapted for use cases that require medical knowledge. Such use cases may include patient interviewing, triaging, clinical decision support, and summarization MedGemma: 4b  has a strong baseline performance compared to similar models of their size, but developers should validate their adapted model’s performance and make necessary improvements before deploying in a production environment.

Adapting MedGemma

MedGemma is a developer model that requires validation on the developer’s intended use case. Based on those validation results, the user will likely need to further adapt the model to improve performance. Below are some types of adaptation developers can use to improve MedGemma’s performance for their use cases.

Prompt engineering/in-context learning

For certain use cases, MedGemma’s baseline performance may be sufficient after careful prompting, potentially including few-shot examples of desirable example responses within the prompt, in other words in-context learning. Prompt engineering may also use MedGemma to break the task into subtasks that can be performed separately. Adaptations using prompt engineering require the same level of validation as any other type of adaptation.

Fine-tuning

MedGemma can be fine-tuned for improved performance on the existing tasks it’s been trained on, or to add additional tasks to its repertoire. For an example of how to fine-tune MedGemma using LoRA (a parameter-efficient fine-tuning technique).

Full details about MedGemma 4b and MedGemma 27B can be found in the MedGemma Technical Report (https://arxiv.org/html/2507.05201v2) .  The abstract for this paper is reproduced below.

Abstract Artificial intelligence (AI) has significant potential in healthcare applications, but its training and deployment are challenging due to healthcare’s diverse data, complex spectrum of possible tasks, and the need to preserve privacy. Foundation models that perform well on various medical tasks and require less task-specific tuning data are critical to accelerating the development of AI for healthcare applications. In this technical report, we introduce MedGemma, a new collection of medical vision–language foundation models based on Gemma 3 4B and 27B. MedGemma demonstrates advanced medical understanding and reasoning on images and text, significantly exceeding the performance of similar-sized generative models and approaching the performance of task-specific models, while maintaining the general capabilities of the Gemma 3 base models. For out-of-distribution tasks, MedGemma achieves 2.6-10% improvements on medical multimodal question answering, 15.5-18.1% improvements on chest X-ray finding classification, and 10.8% improvement on agentic evaluations compared to the base models. Fine-tuning MedGemma further improves performance in subdomains, reducing errors in electronic health record information retrieval by 50% and reaching comparable performance to existing specialized state-of-the-art methods for pneumothorax classification and histopathology patch type classification. We additionally introduce MedSigLIP, a medically-tuned vision encoder derived from SigLIP. MedSigLIP powers the visual understanding capabilities of MedGemma and, as an encoder, it achieves performance comparable to or better than specialized medical image encoders. Taken together, the MedGemma collection provides a strong foundation of medical image and text capabilities, with potential to significantly accelerate medical research and development of downstream applications. More details about the MedGemma collection, including tutorials and instructions for downloading the model weights, can be found at https://goo.gle/MedGemma.

What Is Ollama? A Step-by-Step Guide to Setting Up Your Local AI Powerhouse

Introduction

Generative AI is revolutionizing how we work, but concerns about data privacy and cloud dependency have sparked interest in local AI solutions. Enter Ollama, an open-source platform that lets you run powerful Large Language Models (LLMs) like Llama 3, Mistral, and Gemma right on your own hardware. Whether you’re a developer, translator, or business prioritizing security, Ollama offers a secure, cost-effective way to harness AI without relying on external servers. In this post, we’ll explore what Ollama is, its benefits, and how to set it up on your machine in just a few steps.

What Is Ollama?

Ollama is an open-source framework designed to simplify the deployment and operation of LLMs on local devices, such as your PC or server. It supports a variety of models and works across macOS, Linux, and Windows, making it accessible to a wide range of users. By running AI models locally, Ollama eliminates the need for constant internet connectivity or third-party cloud services, ensuring your data stays private and secure.

Key Features of Ollama:

  • Local Data Control: Your data never leaves your device, reducing risks of breaches or unauthorized access.
  • Customizability: Fine-tune models or adjust parameters to suit specific tasks, like translation or text generation.
  • Cost-Effective: No recurring cloud fees—just use your existing hardware.
  • Seamless Integration: Offers a command-line interface (CLI) and HTTP API for easy integration with applications.
  • Offline Capability: Perfect for secure environments or areas with limited internet access.

Ollama’s containerized environment isolates each model, ensuring compatibility and preventing software conflicts. It’s ideal for industries like healthcare, legal, or finance, where data privacy is critical, as well as for developers and hobbyists experimenting with AI.

Why Use Ollama?

  • Enhanced Privacy: Process sensitive data locally to comply with regulations like GDPR or HIPAA.
  • Reduced Costs: Avoid expensive cloud subscriptions by leveraging your own hardware.
  • Flexibility: Run multiple models and customize them for tasks like coding, content creation, or translation.
  • Security: Minimize exposure to external threats like prompt injection or data leaks.

How to Set Up Ollama: A Step-by-Step Guide

Ready to get started? Follow these simple steps to install and configure Ollama on your machine. This guide assumes basic familiarity with your operating system’s terminal or command line.

Step 1: Check System Requirements

Before installing Ollama, ensure your system meets the minimum requirements:

  • Operating System: macOS, Linux, or Windows.
  • Hardware: At least 8GB of RAM (16GB+ recommended for larger models like Llama 3). A GPU is optional but improves performance.
  • Disk Space: 10GB+ free space for model weights and dependencies.
  • Internet: Required for initial setup and model downloads, but not for runtime.

Step 2: Install Ollama

  • Download Ollama:
    • Visit the official Ollama website or GitHub page.
    • For macOS and Linux, run the following command in your terminal:

bash

curl -fsSL https://ollama.ai/install.sh | sh

  • For Windows, download the installer from the Ollama website.
  • Verify Installation:
    • After installation, check if Ollama is installed by running:

bash

ollama –version

  • You should see the installed version number (e.g., ollama version 0.1.x).

Step 3: Pull a Model

Ollama supports various LLMs, such as Llama 3, Mistral, or Gemma. To download a model:

  • Run the following command to pull a model (e.g., Llama 3):

bash

ollama pull llama3

  • Wait for the download to complete. Model sizes vary (e.g., Llama 3 8B is ~4.7GB).
  • List available models with:

bash

ollama list

Step 4: Run Your First Model

Start using your model with a simple command:

  • Run the model interactively:

bash

ollama run llama3

  • Type a prompt, like “Write a haiku about AI,” and watch the model generate a response.
  • To stop, type /exit or press Ctrl+D.

Alternatively, use the API for programmatic access:

bash

curl http://localhost:11434/api/generate -d ‘{“model”: “llama3”, “prompt”: “What is AI?”}’

Step 5: Customize and Integrate

  • Fine-Tune Prompts: Adjust prompts for specific tasks, like translation or coding. For example:

bash

ollama run llama3 “Translate ‘Hello, world!’ to Spanish”

  • Use the API: Integrate Ollama into your applications via its HTTP API. Check the Ollama API documentation for details.
  • Manage Models: Remove unused models to free up space:

bash

ollama rm llama3

Step 6: Secure Your Setup

To maximize security:

  • Update Regularly: Run ollama pull <model> to get the latest model versions and check for Ollama updates.
  • Firewall Rules: Restrict access to Ollama’s default port (11434) to prevent unauthorized access.
  • Strong Passwords: If exposing Ollama to a network, secure it with authentication.
  • Monitor Vulnerabilities: Stay informed about patches for issues like path traversal or model poisoning (e.g., check Ollama’s GitHub for updates).

Troubleshooting Tips

  • Installation Fails: Ensure you have sufficient disk space and permissions. On Windows, verify WSL2 is properly configured.
  • Model Won’t Run: Check RAM availability and try a smaller model (e.g., Gemma 2B instead of Llama 3 70B).
  • Slow Performance: Consider upgrading your hardware or enabling GPU support if available.

Real-World Example: Secure Translation with Ollama

Imagine you’re a translator working on a confidential legal document. With Ollama, you can run a model like Qwen2 locally to generate draft translations without sending sensitive data to the cloud. Simply install Ollama, pull Qwen2, and run:

bash

ollama run qwen2 “Translate this contract from English to French”

Your data stays on your device, ensuring compliance with privacy regulations and keeping your client’s information secure.

Conclusion

Ollama is a game-changer for anyone looking to harness the power of LLMs while prioritizing privacy and control. Its ease of use, flexibility, and offline capabilities make it a go-to solution for developers, businesses, and individuals alike. By following the steps above, you can set up Ollama in minutes and start exploring the endless possibilities of local AI. Ready to dive in? Install Ollama today and take control of your AI workflow. Share your experience or questions in the comments below, or check out our 75-minute consultation voucher (#) to master Ollama with expert guidance!

Ollama and the Local AI Translator: A Secure Solution for Privacy-Conscious Translators

As generative artificial intelligence (GenAI) transforms industries, its ability to process vast amounts of data and generate human-like outputs has raised significant concerns about data security. Large language models (LLMs), the backbone of GenAI, often require substantial computational resources and access to sensitive data, making privacy and security paramount. In this article, I explore the intersection of GenAI and data security, highlight the advantages of using Ollama to run LLMs securely, and illustrate how the Local AI Translator, built on the Ollama framework, empowers translators to create draft translations while preserving full data security.

GenAI and Data Security: A Critical Balance

GenAI, powered by LLMs, excels in tasks like text generation, translation, and data analysis. However, its reliance on data—often sensitive or proprietary—introduces risks. Cloud-based LLMs, offered by providers like Groq, OpenAI or Google, process data at blazing speeds on external servers, raising concerns about unauthorized access, data breaches, or compliance with regulations like GDPR. The OWASP Top 10 for LLMs highlights vulnerabilities such as prompt injection, data poisoning, and insecure output handling, underscoring the need for robust security measures.

To address these challenges, organizations are turning to solutions that prioritize data control and privacy. Running LLMs locally, rather than in the cloud, minimizes exposure to external threats and ensures compliance with stringent data protection standards. This is where Ollama, an open-source framework, emerges as a game-changer.

What is Ollama?

Ollama is an open-source platform designed to simplify the deployment and operation of LLMs on local hardware, such as personal computers or corporate servers. It supports a wide range of models, including Llama 3, Mistral, and Gemma, and is compatible with macOS, Linux, and Windows. By enabling local execution, Ollama eliminates the need for continuous internet connectivity or reliance on third-party servers, offering a secure and cost-effective alternative to cloud-based AI solutions.

Ollama creates an isolated, containerized environment for each LLM, encapsulating model weights, configuration files, and dependencies. This setup ensures compatibility across systems and prevents conflicts with other software. Key features include:

  • Local Data Control: Data remains within the user’s infrastructure, reducing the risk of breaches.
  • Customizability: Users can fine-tune models and adjust parameters to meet specific needs.
  • Cost-Effectiveness: Eliminates recurring cloud subscription fees.
  • Seamless Integration: Offers a command-line interface and HTTP API for easy application integration.

Ollama’s focus on local deployment makes it ideal for industries like healthcare, finance, and legal services, where data privacy is non-negotiable.

Advantages of Using Ollama for Secure LLM Deployment

Running LLMs with Ollama offers several security and operational advantages, making it a preferred choice for organizations prioritizing data protection:

  • Enhanced Data Privacy: By processing data locally, Ollama ensures that sensitive information never leaves the user’s environment. This eliminates risks associated with cloud-based data transmission and storage, such as interception or unauthorized access.
  • Reduced Attack Surface: Local deployment minimizes reliance on external APIs or networks, significantly reducing vulnerabilities to cyberattacks like prompt injection or DDoS attacks.
  • Complete Control Over Access: Ollama allows organizations to manage who can access models and data, ensuring compliance with internal policies and regulations. Granular permission settings further enhance security.
  • Transparency and Auditability: Running models locally provides visibility into the processing pipeline, enabling organizations to monitor and audit LLM behavior to ensure it aligns with security protocols.
  • Cost Savings: By leveraging existing hardware, Ollama eliminates the need for expensive cloud subscriptions, making it a cost-effective solution for secure AI deployment.
  • Compliance with Regulations: Local data processing helps organizations adhere to data protection laws like GDPR or HIPAA, which mandate strict control over sensitive information.

Despite these advantages, users must maintain general security best practices, such as updating software, using strong passwords, and implementing firewall rules, to fully secure their local environment. Additionally, recent vulnerabilities in Ollama, such as path traversal and model poisoning, highlight the importance of keeping the framework updated and filtering exposed endpoints.

The Local AI Translator: Secure Draft Translations with Ollama

The Local AI Translator, built on the Ollama framework, exemplifies how GenAI can be applied securely in translation workflows. Designed for translators, businesses, and developers, this tool leverages Ollama’s local LLM capabilities to generate draft translations while ensuring complete data security.

How It Works

The Local AI Translator integrates Ollama’s supported LLMs, such as Llama 3 or Qwen2, to process translation tasks on the user’s device. Translators input text, select the target language, and receive draft translations generated by the LLM. The process is entirely offline, ensuring that sensitive content—such as legal documents, medical records, or proprietary business materials—remains secure.

Key features of the Local AI Translator include:

  • Multilingual Support: Handles high-resource languages (e.g., English, Spanish) and low-resource languages, depending on the LLM’s training data.
  • Customizable Outputs: Translators can fine-tune prompts to adjust tone, style, or terminology for specific domains, such as technical or creative translations.
  • User-Friendly Interface: Simplifies interaction with LLMs, making it accessible to non-technical users.
  • Integration with Tools: Supports workflows involving other software, such as CAT (Computer-Assisted Translation) tools, via Ollama’s API.

Preserving Data Security

The Local AI Translator ensures full data security by leveraging Ollama’s local processing capabilities:

  • No Data Transmission: Translations are generated on the user’s device, eliminating the need to send sensitive text to external servers. This is critical for industries handling confidential information.
  • Compliance with Privacy Standards: By keeping data local, the tool supports compliance with regulations like GDPR, ensuring that personal or proprietary data is protected.
  • The Local AI Translator, built on Ollama, exemplifies these benefits by providing translators with a secure, efficient tool for generating draft translations without exposing sensitive data.
  • By adopting solutions like Ollama and the Local AI Translator, organizations and individuals can harness the power of GenAI while maintaining total control over their data. As the AI landscape evolves, prioritizing security will ensure that GenAI remains a trusted tool for innovation and productivity.
  • Secure Collaboration: Translators can work on shared projects with granular access controls, preventing unauthorized access to sensitive documents.
  • Auditability: Organizations can monitor translation processes to ensure data handling aligns with security policies.

Benefits for Translators

The Local AI Translator empowers translators by combining the efficiency of GenAI with robust security:

  • Faster Drafts: LLMs generate high-quality draft translations quickly, reducing manual effort and allowing translators to focus on refining outputs.
  • Secure Handling of Sensitive Content: Translators can process confidential documents, such as legal contracts or medical reports, without risking data exposure.
  • Cost-Effective: Eliminates the need for costly cloud-based translation services, making it accessible for freelance translators and small businesses.
  • Offline Capability: Works without internet connectivity, ideal for translators in remote areas or secure environments.

For example, a freelance translator working on a legal contract can use the Local AI Translator to generate a draft translation from English to Spanish. The process occurs entirely on their laptop, ensuring the contract’s confidentiality. The translator can then refine the draft using their expertise, delivering a polished final product without compromising security. This offline capability makes the Local AI Translator an ideal tool for generating fast translations is crisis and disaster situations when power supplies and internet communications may be down.

Conclusion As GenAI continues to reshape industries, balancing its transformative potential with data security is critical. Ollama addresses this challenge by enabling secure, local deployment of powerful LLMs, offering enhanced privacy. The Local AI Translator combines the benefits of using powerful LLMs with consummate data security.

Fine-tuning: numbers game or fine art?

Nowadays you can’t visit a site on machine learning or deep learning without coming across a page or post about fine-tuning pre-trained models. What’s this all about? Well, in everyday usage, fine-tuning involves making small adjustments to a system or mechanism in order to improve its performance. Think of the guitarist tuning up his instrument before a concert. When machine translation developers  talk about fine-tuning, they are referring to the process of adjusting a machine translation model trained to translate general texts so that it can translate texts in a specific domain better than that generic model. The fine-tuning of computationally expensive pre-trained models is a key aspect of the Hugging Face philosophy.

This work is generally done by continuing the model training process using training data from the specialist field. For example, a dataset comprising parallel sentences in the field of cardiology might be used to empower a general translation model to translate cardiology texts with a reasonable degree of success. This process is also known as domain adaptation or custom machine translation. Its advantage is that we don’t need to train a machine translation system from scratch every time we want to translate documents in a new specialist field as the model parameters are taken over from the baseline model. Given the time and heavy hardware requirements involved in training a new neural machine translation system, this approach seems to represent an ideal solution. But does it always work?

In the past I have successfully used this technique to “specialise” my own Dutch-English NMT models to tackle the translation of particular sets of technical documents for industrial clients. I have recently become interested in the development of machine translation solutions for low-resource languages, particularly African languages.  The Opus-MT project provides models for a great variety of low-resource languages, as one of its stated aims is “to focus on the support of minority and low-resource languages”. The Opus-MT team at the University of Helsinki has provided over 1,000 pre-trained translation models that are free to download and use.

There is evidence that a model fine-tuned on an in-domain dataset can choose the correct translation of a technical term in that domain. The process of fine-tuning a generic English-French model to handle texts in the software domain is described in the Hugging Face course on Transformers (http://tiny.cc/c6k4vz).  I followed the instructions in this course and fine-tuned the model “opus-mt-en-fr” with the “kde4” dataset – a multilingual collection of parallel texts drawn from the manual for KDE, arguably the second-most popular Linux desktop environment after GNOME. My test sentences in the IT domain were translated more accurately after fine-tuning.

For the experiments  described in this post I picked out three African languages included in the Opus-MT project, namely Igbo, Twi and Luganda. Igbo is a member of the Volta-Niger branch of the Niger-Congo family of languages, and is spoken mainly by some 29 million people, mainly in Nigeria. Luganda, or Ganda, is a member of the Bantu branch of Niger-Congo languages, spoken by about 3 million Baganda people, who live mainly in the Buganda region in southern Uganda. Twi is a variety of Akan, a member of the Kwa sub-group of Niger-Congo languages, spoken by about 7 million Twi people, mainly in Ghana. Ganda and Igbo are available in Google Translate and all three languages are available within Facebook Research’s No Language Left Behind (NLLB) project. In view of the paucity of training data available for them, these three languages are said to be “low-resource languages”.

The aim of my  project was to take the baseline Opus-MT models for these three languages and establish whether fine-tuning them on the basis of public datasets would lead to an improvement in the performance of these models. My test sets were taken from the Facebook Research FLORES-200 evaluation set. FLORES-200 consists of translations from 842 distinct web articles, totaling 3001 sentences.  These texts have been professionally translated and it is unlikely that they have been included in the training data used for the baseline Opus-MT models. My approach involved  translating the English version (“eng-Latn”) into my chosen African languages and using the corresponding “devtest texts” as my reference translations. This would give me three baseline BLEU scores. I’m aware of the limitations of evaluating MT output solely on the basis of BLEU but considered this technique adequate for the purposes of this exercise.

I then fine-tuned these models with my chosen datasets. For Igbo there is the Ezeani English-Igbo dataset (https://huggingface.co/datasets/igbo_english_machine_translation). The English-Luganda dataset (https://zenodo.org/record/4764039#.Y-9_n3bP1D8) was created by a team of researchers from AI & Data science research Lab at Makerere University with a team of Luganda teachers, students and freelancers. The dataset for English and Akuapem Twi of 25,421 sentence pairs was built by NLPGhana (https://GhanaNLP.org) and has been augmented with a further 26118 sentences of unknown provenance.

Well, we know that fine-tuning can equip a  model to produce a more accurate technical translation. My questions were: can fine-tuning make a poor model better, and does fine-tuning always improve a good model?  I firstly wanted to examine the effects of such variables as the size of the dataset used for fine-turning and the number of training epochs on a poorly performing “low-resource” model. As I stated above, I took the Opus-MT models for English-Igbo, English-Luganda and English-Twi as my baseline models.  The BLEU scores achieved on the evaluation set these by these models were respectively 6.0, 2.1 and 9.6.  To those used to seeing BLEU scores in the mid-sixities for high-resource language pairs, these numbers look quite dreadful, but they are not uncommon with low-resource language pairs. Could they be improved by fine-tuning with generic datasets that were not available to the Opus-MT developers? Let’s have a look at the numbers below.

LANGUAGE PAIRBASELINE (OPUS-MT)EPOCH 1EPOCH 3EPOCH 5
ENGLISH-IGBO6.007.6010.10
ENGLISH-TWI9.609.309.30
ENGLISH-LUGANDA2.102.803.20
ENGLISH-ROMANIAN *41.6032.6030.90
ENGLISH-FRENCH **47.7044.4043.10

* FINE-TUNED ON WMT16 DATASET
** FINE-TUNED on 1M SUBSET of CALLISON-BURCH DATASET

Table:  BLEU scores for baseline Opus-MT models and after fine-tuning for different epochs

The biggest improvement is seen in the English-Igbo pair. The jump from 6.00 to 11.60 is achieved by fine-tuning for 20 epochs, after which the BLEU score decreases. The English-Luganda pair show a slight increase in the BLEU score – from 2.10 to 3.20 after fine-tuning for 5 epochs but this then decreases irregularly. The score achieved by  Opus-MT baseline is the highest for the English-Twi pair, and its score steadily goes down as the number of epochs increases.  The size (20-30K) and the subject matter (news and Wikipedia material) of the datasets used for fine-tuning were broadly the same. The fact that it took English-Igbo 20 epochs to reach its top score, but the top score was achieved after 5 epochs for English-Luganda might suggest that the performance of the fine-tuning is determined by the strength of the baseline model.  In the case of Opus-MT models (like Igbo and Twi) which have been trained on largely religious texts it is probably more useful to train a new model from scratch and build it up using data augmentation and backtranslation  than to fine-tune these baselines

So far I’ve spoken about poorly performing baseline models involving low-resource African languages. I also examined whether fine-tuning reasonably well performing Opus-MT models for high-resource language pairs with generic datasets would significantly increase their BLEU scores. The baseline OPUS English-Romanian model obtained a respectable 41.60 on the Flores200 test set.  I fine-tuned this model with the English-Romanian subset of the WMT16 dataset using the same basic script I used to train the African models.  The BLEU score on the test set decreased from 41.60 to 32.60 after 1 epoch and to 30.90 after 5 epochs. This suggests it is not enough to fine-tune with a good-quality dataset in broadly the same domain as baseline set to achieve an improvement in model performance.  To investigate this aspect further I took the English-French dataset(20M+ sentence pairs) built by Chris Allison-Burch (https://www.kaggle.com/datasets/dhruvildave/en-fr-translation-dataset) and used a 1 million segment subset of this resource to fine-tune the Opus-MT-en-fr model for one and three epochs.  The resulting “fine-tuned” model produced a decrease in BLEU score of 3.30 and 4.60 respectively.    With these two “good” models for high-resource languages, could the decrease in BLEU score be explained by overfitting?

My conclusion after these simple – and possibly naïve – experiments is that fine-tuning is not an automatic route to a better model. It generally gives the expected results on specialized texts within a chosen domain. It can increase the BLEU score, as in the case of the fine-tuned English-Igbo OPUS model but may result in a lower BLEU score as occurred with the English-Twi model. The baseline Opus-MT models for the high-resource languages – Romanian and French –   produced scores of respectively 41.60 and 47.70 on the test set, which dropped after fine-tuning.  There seems to be no hard and fast rule in this matter. There is no single fine-tuning script that will guarantee an increase in the BLEU score. There is no single dataset that will make a poor model better.  Fine-tuning is not just a numbers game, it’s a fine art.

Example of fine-tuning script derived from a Hugging Face tutorial

import datasets

 from transformers import AutoTokenizer

from datasets import load_dataset

from transformers import DataCollatorForSeq2Seq

from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer

from random import randrange

lugeng_dataset = load_dataset(“csv”, data_files=”luganda-english.csv”)

lugeng_dataset = lugeng_dataset[“train”].map(lambda ex, i: {“id”: i, “translation”: dict(ex)}, remove_columns=[“lg”, “en”], features=datasets.Features({“id”: datasets.Value(“string”), “translation”: datasets

.Translation(languages=[“lg”, “en”])}), with_indices=True,)

lugeng_dataset = lugeng_dataset.train_test_split(test_size=0.2)

tokenizer = AutoTokenizer.from_pretrained(“/home/tel34/nmtgateway/Helsinki-NLP/opus-mt-lg-en”)

source_lang = “lg”

target_lang = “en”

prefix = “translate Luganda to English: “

def preprocess_function(examples):

    inputs = []

    targets = []

    for example in examples[“translation”]:

        if example[source_lang] is not None and example[target_lang] is not None and \

        len(example[source_lang].strip()) > 3 and len(example[target_lang].strip()) > 3:

            inputs.append(prefix + example[source_lang].strip())

            targets.append(example[target_lang].strip())

        else:

            “There is an issue with this segment:”

            print(“Source:”, example[source_lang])

            print(“Target:”, example[target_lang])

            random_num = randrange(10000)

            print(“Replaced with”, random_num)

            inputs.append(prefix + str(random_num))

            targets.append(str(random_num))

    model_inputs = tokenizer(inputs, max_length=128, truncation=True)

    with tokenizer.as_target_tokenizer():

        labels = tokenizer(targets, max_length=128, truncation=True)

        model_inputs[“labels”] = labels[“input_ids”]

    return model_inputs

tokenized_lugeng = lugeng_dataset.map(preprocess_function, batched=True)

model = AutoModelForSeq2SeqLM.from_pretrained(“/home/tel34/nmtgateway/Helsinki-NLP/opus-mt-lg-en”)

data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=model)

training_args = Seq2SeqTrainingArguments(

    output_dir=”./results”,

    evaluation_strategy=”epoch”,

learning_rate=2e-5,

    per_device_train_batch_size=16,

    per_device_eval_batch_size=16,

    weight_decay=0.01,

    save_total_limit=3,

    num_train_epochs=3,

    fp16=True,

)

trainer = Seq2SeqTrainer(

    model=model,

    args=training_args,

    train_dataset=tokenized_lugeng[“train”],

    eval_dataset=tokenized_lugeng[“test”],

    tokenizer=tokenizer,

    data_collator=data_collator,

)

trainer.train()