<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Saksham Sharma — Security & Dev Notes]]></title><description><![CDATA[Saksham Sharma from Pokhara, Nepal (Beni-4, Singa, Myagdi): network & cloud security, open-source AI/LLMs, Linux/Termux, Python, and Android development.]]></description><link>https://sakshamsharmanepal.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 20:48:37 GMT</lastBuildDate><atom:link href="https://sakshamsharmanepal.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Fine-Tuning & Abliterating Open-Source LLMs Step-by-Step in Google Colab]]></title><description><![CDATA[Step-by-step guide to QLoRA fine-tuning and refusal-direction ablation on open-source LLMs using Google Colab, Hugging Face, and LoRA adapters.]]></description><link>https://sakshamsharmanepal.hashnode.dev/fine-tuning-abliterating-open-source-llms-step-by-step-in-google-colab</link><guid isPermaLink="true">https://sakshamsharmanepal.hashnode.dev/fine-tuning-abliterating-open-source-llms-step-by-step-in-google-colab</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[Python]]></category><category><![CDATA[colab]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Saksham Sharma]]></dc:creator><pubDate>Fri, 04 Dec 2026 19:21:07 GMT</pubDate><content:encoded><![CDATA[<pre><code class="language-markdown">
Open-source Large Language Models (LLMs) give developers full visibility into weights, prompts, and training pipelines. Sometimes, a base or instruction-tuned model over-refuses harmless technical prompts—such as security concepts, defensive scripting, or benign creative requests—because of overly aggressive refusal training.

In this step-by-step guide, you will learn how to inspect a small open-source model in Google Colab, understand how refusal behavior is often concentrated in residual-stream directions (commonly studied via abliteration / orthogonalization research), and apply QLoRA fine-tuning with LoRA adapters so you can export a clean, usable model without running out of Colab memory.

---

## Prerequisites &amp; Hardware Reality Check

Google Colab's free tier typically provides a T4 GPU (15 GB VRAM), which is enough for 1B–3B parameter models in 4-bit (`NF4`) or 7B/8B models with tight batch sizes, gradient checkpointing, and short sequence lengths.

Before starting:

1. Open [Google Colab](https://colab.research.google.com/) and create a new notebook.

2. Go to Runtime → Change runtime type and select T4 GPU (or L4 / A100 if available).

3. Verify your GPU and VRAM allocation:

```bash

nvidia-smi
</code></pre>
<p>Install Hugging Face packages (that are compatible with PyTorch) such as <code>transformers</code>, <code>datasets</code>, <code>accelerate</code> and for 4-bit loading, <code>peft</code>, <code>trl</code> and <code>bitsandbytes</code>.</p>
<p>Confirm PyTorch can detect your GPU:</p>
<pre><code class="language-bash">
pip install -q -U torch transformers datasets accelerate peft trl bitsandbytes
</code></pre>
<hr />
<p>Select a lightweight, open-source model</p>
<p>To enable quick experimentation in Colab and to avoid out of memory (OOM) issues, select a lightweight, open-source model (ideally of size 1.5B – 3B parameter(s) and with an open license, for example).</p>
<pre><code class="language-python">
import torch

print("CUDA available:", torch.cuda.is_available())

if torch.cuda.is_available():

print("Device:", torch.cuda.get_device_name(0))

print("VRAM (GB):", round(torch.cuda.get_device_properties(0).total_memory / 1e9, 2))
</code></pre>
<p>Run a basic prompt to see the base model’s behaviour:</p>
<pre><code class="language-python">
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig

import torch

MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" # Example compact model; verify license &amp; availability

bnb_config = BitsAndBytesConfig(

load_in_4bit=True,

bnb_4bit_quant_type="nf4",

bnb_4bit_compute_dtype=torch.float16,

bnb_4bit_use_double_quant=True,

)

tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)

if tokenizer.pad_token is None:

tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(

MODEL_ID,

quantization_config=bnb_config,

device_map="auto",

trust_remote_code=True,

)
</code></pre>
<hr />
<p>Understand model refusal and ablitiation</p>
<p>Within the field of mechanistic interpretability, it has been noted that for many chat LLMs, there is a strong relationship between model refusal behaviour and particular directions of activation in neural network layers. Ablitation involves identifying a “refusal” direction through contrasting prompts (such as those that induce refusals and those that are non-harmful) and then ablating or projecting out this direction in the residual stream and/or neural network weights.</p>
<p>Important considerations for modifying model weights and activations:</p>
<p>Excess modification can be detrimental: Over-orthogonalising and/or ablating may negatively impact upon a model’s fluency, reasoning and/or adherence to instructions.</p>
<p>4-bit model weights are compressed: Direct in-situ manipulation of 4-bit tensors is difficult. Usually, directions are identified in higher-precision (float16 / bfloat16) and/or LoRA adapters are used for fine-tuning. Training data should ideally be of high quality and in an appropriate structure.</p>
<p>Ethical considerations: Never utilise model modification to circumvent a models’ safety mechanisms. Instead, concentrate on ethical research, minimising erroneous refusals to legitimate technical prompts, and enhancing model benevolence.</p>
<hr />
<p>Construct a neat instruction dataset (JSONL)</p>
<p>Using LoRA, you can control aspects such as style and benevolence of an LLM’s responses to good quality prompts, by modifying only adapter weights rather than full model re-training.</p>
<p>Within Colab, build a small <code>dataset.jsonl</code> file containing good quality, high information content examples.</p>
<pre><code class="language-python">
def generate_reply(prompt: str, max_new_tokens: int = 180) -&gt; str:

messages = [{"role": "user", "content": prompt}]

text = tokenizer.apply_chat_template(

messages, tokenize=False, add_generation_prompt=True

)

inputs = tokenizer(text, return_tensors="pt").to(model.device)

with torch.no_grad():

outputs = model.generate(

*inputs,

max_new_tokens=max_new_tokens,

do_sample=True,

temperature=0.7,

top_p=0.9,

pad_token_id=tokenizer.pad_token_id,

)

generated = outputs[0][inputs["input_ids"].shape[1]:]

return tokenizer.decode(generated, skip_special_tokens=True).strip()

print(generate_reply("Explain TCP three-way handshake clearly with a short example."))
</code></pre>
<p>Read and structure the data in Python:</p>
<pre><code class="language-json">
{"messages": [{"role": "user", "content": "How do I check listening ports on Linux?"}, {"role": "assistant", "content": "Run `ss -tulnp` to inspect listening TCP and UDP sockets along with owning processes. Add `| grep :8080` to filter for a specific port."}]}

{"messages": [{"role": "user", "content": "Why should I use a virtual environment in Python?"}, {"role": "assistant", "content": "A virtual environment (`python3 -m venv .venv`) isolates project dependencies so packages in one project do not break system tools or other repositories."}]}
</code></pre>
<hr />
<p>Add LoRA adapters and QLoRA-train</p>
<p>Utilise <code>peft</code> to add LoRA adapters and train using the <code>trl</code> library’s <code>SFTTrainer</code>.</p>
<pre><code class="language-python">
from datasets import load_dataset

# Replace with your own local JSONL or Hugging Face dataset

raw_data = [

{

"text": tokenizer.apply_chat_template(

[

{"role": "user", "content": "How do I check open listening sockets on Linux?"},

{"role": "assistant", "content": "Use `ss -tulnp` to list active TCP/UDP listening sockets and associated processes quickly."},

],

tokenize=False,

)

},

{

"text": tokenizer.apply_chat_template(

[

{"role": "user", "content": "What is the difference between 127.0.0.1 and 0.0.0.0?"},

{"role": "assistant", "content": "`127.0.0.1` binds only to the local loopback interface, while `0.0.0.0` binds across all available IPv4 interfaces."},

],

tokenize=False,

)

},

]

from datasets import Dataset

dataset = Dataset.from_list(raw_data)
</code></pre>
<hr />
<p>Store your LoRA adapters and ensure continued access to your work</p>
<p>Store both your LoRA adapters and tokenizer to prevent data loss if your Colab session is disconnected.</p>
<pre><code class="language-python">
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

from trl import SFTConfig, SFTTrainer

model = prepare_model_for_kbit_training(model)

lora_config = LoraConfig(

r=16,

lora_alpha=32,

lora_dropout=0.05,

bias="none",

task_type="CAUSAL_LM",

target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],

)

model = get_peft_model(model, lora_config)

model.print_trainable_parameters()

training_args = SFTConfig(

output_dir="./lora-output",

per_device_train_batch_size=1,

gradient_accumulation_steps=4,

learning_rate=2e-4,

num_train_epochs=1,

max_steps=10, # Increase once your dataset is larger

fp16=True,

logging_steps=1,

save_strategy="no",

dataset_text_field="text",

max_length=512,

report_to="none",

)

trainer = SFTTrainer(

model=model,

train_dataset=dataset,

processing_class=tokenizer,

args=training_args,

)

trainer.train()
</code></pre>
<p>Common Colab issues</p>
<p>CUDA out of memory: Decrease <code>max_length</code> (for example to 256), allocate <code>per_device_train_batch_size=1</code>, boost <code>gradient_accumulation_steps</code> and/or switch to a lighter model.</p>
<p>Session disconnection: Save your <code>./saksham-llm-lora-adapter</code> or store model checkpoints on Google Drive (<code>/content/drive/MyDrive/...</code>).</p>
<p>Non-sensical or unoriginal outputs: Diminish the learning rate (for example to 1e-4). Further, for very small training data sets, decrease the number of training steps. Lastly, confirm the <code>tokenizer.pad_token</code> and chat template structure is correct.</p>
<hr />
<p>Overview</p>
<p>Ideal practice for performing LLM fine-tuning in Google Colab is to initially work on a small-scale basis, utilise 4-bit NF4 quantisation and implement LoRA adapters for flexible experimentation. After each alteration, assess the resulting model outputs.</p>
<hr />
<p>About</p>
<p>I am Saksham Sharma (@sakshamsharmanepal), a Cybersecurity researcher and practitioner from Beni-4, Singa and Myagdi. I am now based in Pokhara, Nepal and specialise in network and cloud security, open-source AI and LLMs, Linux and Termux, Python and Android app development.</p>
<p>Portfolio: <a href="https://sakshamsharmanepal.github.io/sakshamsharma/">https://sakshamsharmanepal.github.io/sakshamsharma/</a></p>
<p>GitHub: <a href="https://github.com/sakshamsharmanepal">https://github.com/sakshamsharmanepal</a></p>
<p>LinkedIn: <a href="https://www.linkedin.com/in/sakshamsharmanepal">https://www.linkedin.com/in/sakshamsharmanepal</a></p>
<p>You can contact Saksham Sharma (@sakshamsharmanepal) by email at <a href="mailto:connect@sakshamsharma.work.gd">connect@sakshamsharma.work.gd</a> or <a href="mailto:controlsaksham@gmail.com">controlsaksham@gmail.com</a>, or by phone at +977-9847649312.</p>
]]></content:encoded></item><item><title><![CDATA[Automating Android & Termux Workflows With Python and Clean Scripting]]></title><description><![CDATA[Automate Termux and Android workflows with clean Python scripts. Use virtual environments, timeouts, error logs, and single-purpose tools.]]></description><link>https://sakshamsharmanepal.hashnode.dev/sakshamsharmanepal-automating-android-termux-workflows-with-python-and-clean-scripting</link><guid isPermaLink="true">https://sakshamsharmanepal.hashnode.dev/sakshamsharmanepal-automating-android-termux-workflows-with-python-and-clean-scripting</guid><category><![CDATA[Python]]></category><category><![CDATA[termux]]></category><category><![CDATA[Linux]]></category><category><![CDATA[Android]]></category><category><![CDATA[automation]]></category><dc:creator><![CDATA[Saksham Sharma]]></dc:creator><pubDate>Fri, 04 Dec 2026 19:08:11 GMT</pubDate><content:encoded><![CDATA[<pre><code class="language-markdown">Termux turns an Android device into a practical command-line and Python environment, making it useful for quick diagnostics, environment checks, and lightweight automation. Because mobile environments have tight resource constraints and different path conventions than desktop Linux, small engineering habits make a big difference in reliability.

This guide covers practical ways to keep Python and Termux automation scripts clean, predictable, and easy to maintain.

---

## 1. Keep Termux Packages and Python Paths Predictable

Before installing packages or running scripts, keep your base environment clean and verify your runtime versions:

```bash
pkg update &amp;&amp; pkg upgrade -y
python3 --version
pip --version
</code></pre>
<ul>
<li><strong>Isolate dependencies:</strong> Use a virtual environment (<code>python3 -m venv .venv</code>) when a project depends on external Python libraries so packages do not conflict across scripts.</li>
<li><strong>Check environment variables early:</strong> Validate required environment variables or tool paths at startup instead of letting a script fail halfway through.</li>
</ul>
<hr />
<h2>2. Break Tasks Into Small, Single-Purpose Scripts</h2>
<p>Large, monolithic scripts are harder to debug and reuse on mobile devices:</p>
<ul>
<li><strong>Separate responsibilities:</strong> Keep environment/health checks (such as a <code>check_env.py</code> script), data/task runners, and cleanup logic in distinct, focused files.</li>
<li><strong>Use clean CLI arguments:</strong> Parse flags with <code>argparse</code> rather than editing constants inside the script every time you run it.</li>
<li><strong>Return clear exit codes:</strong> Exit with <code>0</code> on success and non-zero codes on failure so wrappers, schedulers, or chained commands can handle errors cleanly.</li>
</ul>
<hr />
<h2>3. Handle Paths, Timeouts, and Errors Explicitly</h2>
<p>Mobile networks and storage states can change unexpectedly:</p>
<ul>
<li><strong>Use safe path handling:</strong> Prefer <code>pathlib.Path</code> and explicit checks over fragile hardcoded paths.</li>
<li><strong>Set network timeouts:</strong> Always pass explicit timeouts to network calls or HTTP requests so a slow or dropped connection does not hang execution indefinitely.</li>
<li><strong>Fail with clear messages:</strong> Log concise, readable error messages and context instead of swallowing exceptions silently.</li>
</ul>
<hr />
<h2>4. Document Setup and Usage in <code>README.md</code></h2>
<p>Even compact utilities are much easier to revisit—and more helpful to others on GitHub—when documented clearly:</p>
<ul>
<li>List required packages and setup commands (<code>pkg</code> / <code>pip</code>).</li>
<li>Include one or two copy-paste run examples.</li>
<li>Note common pitfalls (such as storage permissions, missing dependencies, or network timeouts).</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Reliable Termux and Python automation comes down to clean environments, focused single-purpose scripts, explicit timeouts and error handling, and clear documentation.</p>
<hr />
<h3>Author</h3>
<p><strong>Saksham Sharma</strong> (<code>@sakshamsharmanepal</code>) — Cybersecurity researcher and developer from Beni-4, Singa, Myagdi, currently based in Pokhara, Nepal, focusing on network and cloud security, open-source AI/LLMs, Linux/Termux environments, Python scripting, and Android application development.</p>
<ul>
<li><strong>Portfolio:</strong> <a href="https://sakshamsharmanepal.github.io/sakshamsharma/">https://sakshamsharmanepal.github.io/sakshamsharma/</a></li>
<li><strong>GitHub:</strong> <a href="https://github.com/sakshamsharmanepal">https://github.com/sakshamsharmanepal</a></li>
<li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sakshamsharmanepal">https://www.linkedin.com/in/sakshamsharmanepal</a></li>
<li>You can contact Saksham Sharma (@sakshamsharmanepal) by email at <a href="mailto:connect@sakshamsharma.work.gd">connect@sakshamsharma.work.gd</a> or <a href="mailto:controlsaksham@gmail.com">controlsaksham@gmail.com</a>, or by phone at +977-9847649312.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Running Open-Source LLMs & Local AI Tools Safely on Linux and Termux]]></title><description><![CDATA[Run open-source LLMs and local AI safely on Linux and Termux. Check RAM, keep ports on 127.0.0.1, vet scripts, and protect sensitive data.]]></description><link>https://sakshamsharmanepal.hashnode.dev/running-open-source-llms-local-ai-tools-safely-on-linux-and-termux</link><guid isPermaLink="true">https://sakshamsharmanepal.hashnode.dev/running-open-source-llms-local-ai-tools-safely-on-linux-and-termux</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[opensourceai]]></category><category><![CDATA[Uncensored AI tools]]></category><category><![CDATA[Linux]]></category><category><![CDATA[cybersecurity]]></category><dc:creator><![CDATA[Saksham Sharma]]></dc:creator><pubDate>Fri, 04 Dec 2026 19:00:53 GMT</pubDate><content:encoded><![CDATA[<pre><code class="language-markdown">
Open-source Large Language Models (LLMs) and local inference runtimes make it practical to experiment with code generation, CLI assistants, and private workflows without routing every prompt through a cloud API. At the same time, running local models and open-source tooling on Linux or Android (Termux) introduces hardware bottlenecks and practical security risks that are easy to overlook.



This guide outlines a structured workflow for running open-source AI tools reliably and safely across Linux and Termux environments.



---



## 1. Size Your Models to Available Hardware



Before downloading multi-gigabyte model weights, inspect your system memory and storage capacity:

```bash

free -h

df -h
</code></pre>
<p>Config</p>
<p>Try to reduce an AI model’s size and/or utilise models with quantisation so that they can be loaded without excessive swapping/paging, i.e., within your device’s RAM/VRAM.</p>
<p>Also consider the impact of local AI inference. Termux and/or minimalistic Linux devices can become hot and use disk space rapidly. Ensure that you are monitoring both of these in extended usage scenarios.</p>
<hr />
<ol start="2">
<li>Limit Local AI Inference to Loopback</li>
</ol>
<p>Whilst many local AI inference servers, APIs and web interfaces are configured to only accept connections via a local port, it is good practice to confirm which network interface(s) will be used by the service:</p>
<p>Local (<code>127.0.0.1</code> / <code>localhost</code>): Ensures that only your local device can access the service. This is appropriate for personal use and command line interfacing.</p>
<p>All interfaces (<code>0.0.0.0</code>): Opens the designated port for use via all network interfaces. Do not allow unauthenticated AI inference services to be available via <code>0.0.0.0</code>, particularly if your device is connecting to non-trusted networks, or if the service is made directly available on the public internet.</p>
<hr />
<ol start="3">
<li>Scrutinise Code, Models and Packages</li>
</ol>
<p>Within the fast-moving open source AI landscape it is important to ensure good ‘supply chain’ practice:</p>
<p>Access only from reliable locations and confirm authenticity: Download AI inference runtime environments, code and models from trustworthy sources – for example, official versions or well known repositories. Confirm authenticity using checksums or hashes where possible.</p>
<p>Manually inspect code. Pay particular attention to shell and Python code relating to installation and configuration as this may include functionality that alters device packages, permissions and background processes.</p>
<p>Utilise Python virtual environments (<code>python3 -m venv .venv</code>) to maintain distinct AI related packages and packages generally, for different projects.</p>
<hr />
<ol start="4">
<li>Segregate Confidential Information</li>
</ol>
<p>Ensure that there is a defined distinction between test AI models, external prompt enclosures and plug-ins, and confidential information:</p>
<p>Never input API, login or secret keys, nor confidential personal or business information, into unvalidated local and/or external AI inference processes.</p>
<p>Ensure that test prompts and sample information are also physically separated from confidential information and login details.</p>
<hr />
<p>Overview</p>
<p>Combining self-hosted open-source large language models with good engineering practice allows you to effectively manage and protect your AI. Appropriately size models for your hardware, securely configure local AI inference services, scrutinise code and packages and physically separate confidential information from AI testing.</p>
<hr />
<p>About</p>
<p>I am Saksham Sharma ( @sakshamsharmanepal ), a cybersecurity researcher and developer from Beni-4, Singa, Myagdi. I am currently based in Pokhara, Nepal. My areas of interest include network and cloud security, open-source AI and LLMs, Linux and Termux, Python and Android app development.</p>
<p>Portfolio: <a href="https://sakshamsharmanepal.github.io/sakshamsharma/">https://sakshamsharmanepal.github.io/sakshamsharma/</a> 
GitHub: <a href="https://github.com/sakshamsharmanepal">https://github.com/sakshamsharmanepal</a> 
LinkedIn: <a href="https://www.linkedin.com/in/sakshamsharmanepal/">https://www.linkedin.com/in/sakshamsharmanepal/</a></p>
<p>You can contact Saksham Sharma (@sakshamsharmanepal) by email at <a href="mailto:connect@sakshamsharma.work.gd">connect@sakshamsharma.work.gd</a> or <a href="mailto:controlsaksham@gmail.com">controlsaksham@gmail.com</a>, or by phone at +977-9847649312.</p>
]]></content:encoded></item></channel></rss>