In modern software development, AI-powered tools are becoming valuable companions for programmers. DeepSeek R1 is one such tool that helps you generate code snippets, fix bugs, and automate repetitive programming tasks. Instead of spending hours debugging or writing boilerplate code, you can offload these tasks to DeepSeek and focus on solving higher-level problems.
In this tutorial, you’ll learn how to use DeepSeek R1 for Code generation and debugging on an Ubuntu 24.04 GPU server.
Prerequisites
- An Ubuntu 24.04 server with an NVIDIA GPU.
- A non-root user or a user with sudo privileges.
- NVIDIA drivers are installed on your server.
Step 1 – Install System Dependencies
Before setting up DeepSeek R1, you need to install the essential packages required for building and running Python applications on Ubuntu 24.04.
1. Update the package index.
apt update -y
2. Install required system packages.
apt install -y git curl wget build-essential python3 python3-pip python3-venv
Step 2 – Clone and Set Up DeepSeek R1 Repository
With the dependencies installed, the next step is to get a copy of the DeepSeek R1 project from GitHub. This repository contains the scripts and configuration files you’ll use to run the model.
1. Clone the DeepSeek R1 GitHub repository.
git clone https://github.com/deepseek-ai/DeepSeek-R1.git
2. Navigate to the downloaded repository.
cd DeepSeek-R1
3. Create a virtual environment for your project.
python3 -m venv venv
4. Activate the virtual environment.
source venv/bin/activate
5. Upgrade pip to the latest version.
pip install --upgrade pip
6. Next, install PyTorch compiled with CUDA 12.4 so the model can run on your GPU.
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
7. Finally, install the Hugging Face ecosystem libraries.
pip install transformers accelerate huggingface_hub
8. Verify that PyTorch is correctly installed.
python3 -c "import torch; print(torch.__version__)"
Output.
2.6.0+cu124
Step 3 – Authenticate with Hugging Face
DeepSeek R1 models are hosted on Hugging Face, so you’ll need to log in and download them before use. Authentication ensures you can access the model files and keep them locally on your server.
1. First, log in using your Hugging Face token.
huggingface-cli login
When prompted, enter your token.
2. Next, download the DeepSeek Coder model to a local directory.
huggingface-cli download deepseek-ai/deepseek-coder-1.3b-base --local-dir ./deepseek-coder
3. Once the download finishes, check if the model files exist.
ls ./deepseek-coder | grep bin
Output.
pytorch_model.bin
The model is now stored locally and ready for use. In the next step, you’ll generate your first piece of code with DeepSeek R1.
Step 4 – Generate Code with DeepSeek R1
Now that the model is downloaded, let’s generate Python code using DeepSeek R1. We’ll create a script that sends a natural language prompt to the model and retrieves executable code.
1. Create a new file called deepseek_generate.py.
nano deepseek_generate.py
Add the following content:
from transformers import AutoTokenizer, AutoModelForCausalLM import torch # Load from local directory model_name = "./deepseek-coder" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, device_map="auto", dtype=torch.float16, trust_remote_code=True ) prompt = "Write a Python function that checks if a number is prime." inputs = tokenizer(prompt, return_tensors="pt").to("cuda") with torch.no_grad(): outputs = model.generate(**inputs, max_length=150) generated_code = tokenizer.decode(outputs[0], skip_special_tokens=True) print("\n=== Generated Code ===\n") print(generated_code)
2. Run the script.
python3 deepseek_generate.py
You should see output like this:
=== Generated Code === Write a Python function that checks if a number is prime. The function should take a number as input and return True if the number is prime and False otherwise. You can assume that the input number is an integer. Example: Input: 19 Output: True Input: 11 Output: False def is_prime(number): if number == 1: return False for i in range(2, number): if number % i == 0: return False return True print(is_prime(19)) print(is_prime(11))
✅ Congratulations! You just generated your first working Python function using DeepSeek R1.
Step 5 – Debug Python Code with DeepSeek R1
DeepSeek R1 can also automatically repair broken Python scripts. This is especially useful when you hit runtime errors or logic bugs. Let’s try it with a simple example.
1. Create a buggy script.
nano buggy_script.py
Add the following code.
def divide(a, b): return a / b print(divide(5, 0))
2. Create the debugger script.
nano deepseek_debug.py
Add the following code.
from transformers import AutoTokenizer, AutoModelForCausalLM import sys, torch, re model_name = "./deepseek-coder" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, device_map="auto", dtype=torch.float16, trust_remote_code=True ) if len(sys.argv) < 2: print("Usage: python deepseek_debugger.py ") sys.exit(1) filename = sys.argv[1] with open(filename, "r") as f: buggy_code = f.read() prompt = ( "Fix the following Python code.\n" "Respond with ONLY Python code inside a ```python ... ``` block.\n" "Do not include explanations.\n\n" f"{buggy_code}" ) inputs = tokenizer(prompt, return_tensors="pt").to("cuda") with torch.no_grad(): outputs = model.generate(**inputs, max_length=500) text_output = tokenizer.decode(outputs[0], skip_special_tokens=True) # Find all python code blocks matches = re.findall(r"```(?:python)?(.*?)```", text_output, re.DOTALL) if matches: # Take the last block (most complete version) code_output = matches[-1].strip() else: # fallback: treat the entire output as code code_output = text_output.strip() # Save fixed code with open("fixed_buggy_script.py", "w") as f: f.write(code_output) print("\n=== Fixed Code (saved to fixed_buggy_script.py) ===\n") print(code_output)
3. Run the debugger
python3 deepseek_debug.py buggy_script.py
Output.
Setting `pad_token_id` to `eos_token_id`:32014 for open-end generation. === Fixed Code (saved to fixed_buggy_script.py) === def divide(a, b): if b == 0: return None return a / b print(divide(5, 5))
✅ DeepSeek R1 automatically fixed the bug and saved the corrected code in fixed_buggy_script.py.
Step 6 – Create the CLI Code Generator
DeepSeek R1 can also be used as a CLI tool where you pass prompts directly from the command line, and it generates working Python code for you. This makes it convenient to quickly create code snippets without needing to write additional scripts.
1. Create a file called deepseek_codegen.py.
nano deepseek_codegen.py
Add the following code.
from transformers import AutoTokenizer, AutoModelForCausalLM import sys, torch, re model_name = "./deepseek-coder" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, device_map="auto", dtype=torch.float16, trust_remote_code=True ) prompt = " ".join(sys.argv[1:]) # Force model to return code only prompt = f"{prompt}\n\nReturn only valid Python code. No text, no explanations." inputs = tokenizer(prompt, return_tensors="pt").to("cuda") with torch.no_grad(): outputs = model.generate(**inputs, max_length=300) text_output = tokenizer.decode(outputs[0], skip_special_tokens=True) # Try to extract code from triple backticks match = re.search(r"```(?:python)?(.*?)```", text_output, re.DOTALL) if match: code_output = match.group(1).strip() else: # fallback: assume whole output is code code_output = text_output.strip() with open("generated_code.py", "w") as f: f.write(code_output) print("\n=== Generated Code (saved to generated_code.py) ===\n") print(code_output)
2. Run the following command to generate a Fibonacci script.
python3 deepseek_codegen.py "Print first 20 Fibonacci numbers"
Output.
=== Generated Code (saved to generated_code.py) === def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) for i in range(20): print(fib(i))
3. Execute the generated script.
python3 generated_code.py
Output.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Conclusion
In this tutorial, you learned how to set up and use DeepSeek R1 on an Ubuntu 24.04 GPU server for real-world coding tasks. Starting from installing system dependencies, creating a Python virtual environment, and authenticating with Hugging Face, you successfully downloaded the DeepSeek Coder model and ran it locally on your GPU.
With this setup, your GPU server effectively becomes an AI coding assistant, capable of speeding up development, reducing debugging time, and even acting as a boilerplate generator for everyday programming tasks.