


Fine-Tuning Large Language Models (LLMs) with .NET Core, Python, and Azure
Table of Contents
- Introduction
- Why fine-tune large language models?
- Solution Overview
- Environment Settings
- Training and fine-tuning using Python
- Integrate fine-tuned models in .NET Core
- Deploy to Azure
- Best Practices
- Conclusion
-
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.
-
Why fine-tune large language models?
-
Domain Specificity: LLM can be fine-tuned to use industry-specific terminology, product names, or jargon.
-
Performance improvements: Fine-tuning often reduces errors and improves relevancy in use cases such as customer service, research, and analytics.
-
Reduce costs: Instead of building a model from scratch, you can customize an existing powerful LLM.
-
Improving efficiency: You take advantage of pre-trained weights and only adjust the final layer or parameters, thus speeding up the process.
-
Solution Overview
Components and Technologies
-
Python for fine-tuning
- Commonly used libraries (e.g. Hugging Face Transformers, PyTorch)
- Simplified the process of loading and tuning pre-trained models
-
.NET Core C# for integration
- Expose a backend service or API for fine-tuning the model
- Strongly typed language, familiar to many enterprise developers
-
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
-
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.
-
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>
5.2 Install dependencies
<code>pip install torch transformers azureml-sdk</code>
5.3 Create an Azure Machine Learning workspace
- Resource Group and Workspace:
<code> az group create --name LLMFinetuneRG --location eastus az ml workspace create --name LLMFinetuneWS --resource-group LLMFinetuneRG</code>
- 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>
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>
At this point, your fine-tuned model is stored in Azure Machine Learning for easy access and version control.
-
Integrate fine-tuned models in .NET Core
6.1 Create .NET Core Web API project
<code>dotnet new webapi -n FineTunedLLMApi cd FineTunedLLMApi</code>
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>
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>
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>
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>
-
Deploy to Azure
-
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>
-
Azure Function (optional):
- Ideal for running serverless, event-driven logic if your usage is intermittent or scheduled.
-
Azure Kubernetes Service (AKS) (Advanced):
- Ideal for large-scale deployment.
- Containerize your application using Docker and push it to Azure Container Registry (ACR).
-
Best Practices
-
Data Privacy: Ensure responsible handling of sensitive or proprietary data, especially during model training.
-
Monitoring and Logging: Integrate with Azure Application Insights to monitor performance, track usage, and detect anomalies.
-
Security: Use Azure Key Vault to store keys (API keys, connection strings).
-
Model Versioning: Track different fine-tuned versions of your model in Azure ML; rollback to older versions if needed.
-
Hint Engineering: Refine your hints to get the best results from your fine-tuned model.
-
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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 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? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

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)...
