


Fine-Tuning Large Language Models (LLMs) with .NET Core, Python, and Azure
Jan 14, 2025 am 07:11 AMTable 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) # 加載自定義數(shù)據(jù)集(本地或來自 Azure 存儲(chǔ)) # 示例:Azure ML 中的文本文件或數(shù)據(jù)集 train_texts = ["此處輸入您的特定領(lǐng)域文本..."] # 簡化版 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() # 保存微調(diào)后的模型 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

Undress AI Tool
Undress images for free

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

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

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)

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

Iterators are objects that implement __iter__() and __next__() methods. The generator is a simplified version of iterators, which automatically implement these methods through the yield keyword. 1. The iterator returns an element every time he calls next() and throws a StopIteration exception when there are no more elements. 2. The generator uses function definition to generate data on demand, saving memory and supporting infinite sequences. 3. Use iterators when processing existing sets, use a generator when dynamically generating big data or lazy evaluation, such as loading line by line when reading large files. Note: Iterable objects such as lists are not iterators. They need to be recreated after the iterator reaches its end, and the generator can only traverse it once.

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

A common method to traverse two lists simultaneously in Python is to use the zip() function, which will pair multiple lists in order and be the shortest; if the list length is inconsistent, you can use itertools.zip_longest() to be the longest and fill in the missing values; combined with enumerate(), you can get the index at the same time. 1.zip() is concise and practical, suitable for paired data iteration; 2.zip_longest() can fill in the default value when dealing with inconsistent lengths; 3.enumerate(zip()) can obtain indexes during traversal, meeting the needs of a variety of complex scenarios.

InPython,iteratorsareobjectsthatallowloopingthroughcollectionsbyimplementing__iter__()and__next__().1)Iteratorsworkviatheiteratorprotocol,using__iter__()toreturntheiteratorand__next__()toretrievethenextitemuntilStopIterationisraised.2)Aniterable(like

Assert is an assertion tool used in Python for debugging, and throws an AssertionError when the condition is not met. Its syntax is assert condition plus optional error information, which is suitable for internal logic verification such as parameter checking, status confirmation, etc., but cannot be used for security or user input checking, and should be used in conjunction with clear prompt information. It is only available for auxiliary debugging in the development stage rather than substituting exception handling.

TypehintsinPythonsolvetheproblemofambiguityandpotentialbugsindynamicallytypedcodebyallowingdeveloperstospecifyexpectedtypes.Theyenhancereadability,enableearlybugdetection,andimprovetoolingsupport.Typehintsareaddedusingacolon(:)forvariablesandparamete

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.
