Table of Contents
Table of Contents
Introduction
Why fine-tune large language models?
Solution Overview
Components and Technologies
Environment settings
Prerequisites
Training and fine-tuning using Python
5.1 Set up virtual environment
5.2 Install dependencies
5.3 Create an Azure Machine Learning workspace
5.4 Fine-tuning script (train.py)
5.5 Register model in Azure
Integrate fine-tuned models in .NET Core
6.1 Create .NET Core Web API project
6.2 Add dependencies
6.3 ModelConsumerService.cs
6.4 LLMController.cs
6.5 Configuring .NET Core Applications
Deploy to Azure
Best Practices
Conclusion
Home Backend Development Python Tutorial Fine-Tuning Large Language Models (LLMs) with .NET Core, Python, and Azure

Fine-Tuning Large Language Models (LLMs) with .NET Core, Python, and Azure

Jan 14, 2025 am 07:11 AM

Fine-Tuning Large Language Models (LLMs) with .NET Core, Python, and Azure

Table of Contents

  1. Introduction
  2. Why fine-tune large language models?
  3. Solution Overview
  4. Environment Settings
  5. Training and fine-tuning using Python
  6. Integrate fine-tuned models in .NET Core
  7. Deploy to Azure
  8. Best Practices
  9. Conclusion

  1. Introduction

Large-scale language models (LLMs) have received widespread attention for their ability to understand and generate human-like text. However, many organizations have unique, domain-specific data sets and vocabularies that may not be fully captured by generic models. Fine-tuning enables developers to adapt these large models to specific environments or industries, improving accuracy and relevancy.

This article explores how to fine-tune an LLM using Python, then integrate and deploy the resulting model into a .NET Core C# application, all done on Microsoft Azure for scalability and Convenience.


  1. Why fine-tune large language models?

  2. Domain Specificity: LLM can be fine-tuned to use industry-specific terminology, product names, or jargon.

  3. Performance improvements: Fine-tuning often reduces errors and improves relevancy in use cases such as customer service, research, and analytics.

  4. Reduce costs: Instead of building a model from scratch, you can customize an existing powerful LLM.

  5. Improving efficiency: You take advantage of pre-trained weights and only adjust the final layer or parameters, thus speeding up the process.


  1. Solution Overview

Components and Technologies

  1. Python for fine-tuning

    • Commonly used libraries (e.g. Hugging Face Transformers, PyTorch)
    • Simplified the process of loading and tuning pre-trained models
  2. .NET Core C# for integration

    • Expose a backend service or API for fine-tuning the model
    • Strongly typed language, familiar to many enterprise developers
  3. Azure Services

    • Azure Machine Learning for training and model management
    • Azure Storage for data and model artifacts
    • Azure App Service or Azure Function for hosting .NET Core applications
    • Azure Key Vault (optional) for protecting credentials

  1. Environment settings

Prerequisites

  • Azure Subscription: Required to create resources such as Machine Learning Workspace and App Service.
  • Python 3.8 : Installed locally for model fine-tuning.
  • .NET 6/7/8 SDK: For creating and running .NET Core C# applications.
  • Visual Studio 2022 or Visual Studio Code: Recommended IDE.
  • Azure CLI: Used to configure and manage Azure services through the terminal.
  • Docker (optional): Can be used to containerize your application if needed.

  1. Training and fine-tuning using Python

This example uses Hugging Face Transformers - one of the most widely adopted LLM fine-tuning libraries.

5.1 Set up virtual environment

<code>python -m venv venv
source venv/bin/activate  # 在 Windows 上:venv\Scripts\activate</code>
Copy after login
Copy after login

5.2 Install dependencies

<code>pip install torch transformers azureml-sdk</code>
Copy after login

5.3 Create an Azure Machine Learning workspace

  1. Resource Group and Workspace:
<code>   az group create --name LLMFinetuneRG --location eastus
   az ml workspace create --name LLMFinetuneWS --resource-group LLMFinetuneRG</code>
Copy after login
  1. Configure the local environment to connect to the workspace (using a config.json file or environment variables).

5.4 Fine-tuning script (train.py)

<code>import os
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
from azureml.core import Workspace, Run

# 连接到 Azure ML
ws = Workspace.from_config()
run = Run.get_context()

model_name = "gpt2"  # 示例模型
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

# 加载自定义数据集(本地或来自 Azure 存储)
# 示例:Azure ML 中的文本文件或数据集
train_texts = ["此处输入您的特定领域文本..."]  # 简化版
train_encodings = tokenizer(train_texts, truncation=True, padding=True)

class CustomDataset(torch.utils.data.Dataset):
    def __init__(self, encodings):
        self.encodings = encodings
    def __len__(self):
        return len(self.encodings["input_ids"])
    def __getitem__(self, idx):
        return {k: torch.tensor(v[idx]) for k, v in self.encodings.items()}

train_dataset = CustomDataset(train_encodings)

training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    save_steps=100,
    logging_steps=100
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
)

trainer.train()

# 保存微调后的模型
trainer.save_model("./fine_tuned_model")
tokenizer.save_pretrained("./fine_tuned_model")</code>
Copy after login

5.5 Register model in Azure

<code>from azureml.core.model import Model

model = Model.register(
    workspace=ws,
    model_path="./fine_tuned_model",
    model_name="myFineTunedLLM"
)</code>
Copy after login

At this point, your fine-tuned model is stored in Azure Machine Learning for easy access and version control.


  1. Integrate fine-tuned models in .NET Core

6.1 Create .NET Core Web API project

<code>dotnet new webapi -n FineTunedLLMApi
cd FineTunedLLMApi</code>
Copy after login

6.2 Add dependencies

  • HttpClient for calling Azure endpoints or local inference API
  • Newtonsoft.Json (if you prefer to use JSON.NET for serialization)
  • Azure.Storage.Blobs or Azure.Identity for secure access to Azure resources
<code>dotnet add package Microsoft.Extensions.Http
dotnet add package Microsoft.Azure.Storage.Blob
dotnet add package Newtonsoft.Json</code>
Copy after login

6.3 ModelConsumerService.cs

Assume you have deployed your fine-tuned model as a web service (for example, using Azure Container Instance or a custom endpoint in Azure ML). The following code snippet calls the service to get completion results.

<code>using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class ModelConsumerService
{
    private readonly HttpClient _httpClient;

    public ModelConsumerService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("FineTunedModel");
    }

    public async Task<string> GetCompletionAsync(string prompt)
    {
        var requestBody = new { prompt = prompt };
        var content = new StringContent(
            JsonConvert.SerializeObject(requestBody),
            Encoding.UTF8, 
            "application/json");

        var response = await _httpClient.PostAsync("/predict", content);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}</code>
Copy after login

6.4 LLMController.cs

<code>using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class LLMController : ControllerBase
{
    private readonly ModelConsumerService _modelService;

    public LLMController(ModelConsumerService modelService)
    {
        _modelService = modelService;
    }

    [HttpPost("complete")]
    public async Task<IActionResult> CompletePrompt([FromBody] PromptRequest request)
    {
        var result = await _modelService.GetCompletionAsync(request.Prompt);
        return Ok(new { Completion = result });
    }
}

public class PromptRequest
{
    public string Prompt { get; set; }
}</code>
Copy after login

6.5 Configuring .NET Core Applications

In Program.cs or Startup.cs:

<code>var builder = WebApplication.CreateBuilder(args);

// 注册 HttpClient
builder.Services.AddHttpClient("FineTunedModel", client =>
{
    client.BaseAddress = new Uri("https://your-model-endpoint/");
});

// 注册 ModelConsumerService
builder.Services.AddTransient<ModelConsumerService>();

builder.Services.AddControllers();
var app = builder.Build();

app.MapControllers();
app.Run();</code>
Copy after login

  1. Deploy to Azure

  2. Azure App Service:

    • For many .NET Core applications, this is the easiest path.
    • Create a new Web App from the Azure portal or via the CLI.
<code>python -m venv venv
source venv/bin/activate  # 在 Windows 上:venv\Scripts\activate</code>
Copy after login
Copy after login
  1. Azure Function (optional):

    • Ideal for running serverless, event-driven logic if your usage is intermittent or scheduled.
  2. Azure Kubernetes Service (AKS) (Advanced):

    • Ideal for large-scale deployment.
    • Containerize your application using Docker and push it to Azure Container Registry (ACR).

  1. Best Practices

  2. Data Privacy: Ensure responsible handling of sensitive or proprietary data, especially during model training.

  3. Monitoring and Logging: Integrate with Azure Application Insights to monitor performance, track usage, and detect anomalies.

  4. Security: Use Azure Key Vault to store keys (API keys, connection strings).

  5. Model Versioning: Track different fine-tuned versions of your model in Azure ML; rollback to older versions if needed.

  6. Hint Engineering: Refine your hints to get the best results from your fine-tuned model.


  1. Conclusion

Fine-tune LLM using Python and Azure Machine Learning and then integrate them into .NET Core applications, allowing you to build powerful domain-specific AI solutions. This combination is an excellent choice for organizations looking to take advantage of Python’s AI ecosystem and the enterprise capabilities of .NET, all powered by the extensibility of Azure.

With careful planning for security, data governance, and DevOps, you can launch a production-ready solution that meets real-world needs, delivering accurate domain-specific language functionality in a powerful and easy-to-maintain framework.

The above is the detailed content of Fine-Tuning Large Language Models (LLMs) with .NET Core, Python, and Azure. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles