ref
quick-search reference — copy, paste, move on
428 commands · 101 topics·7 categories·/ search·Ctrl K palette, anywhere on the site
click any line to copy it · dashed args are editable in place · ↑↓ + Enter
find with the filters you actually use
search a tree, show context, filter by file type
in-place edits without opening an editor
extract columns, sum, filter rows
the flags no one remembers
local ↔ remote sync; trailing slash on src matters
reach a remote-only service locally, or expose a local one
files and directories, both directions
du/df combos for finding the big directories
find and kill whatever is holding a port
who is eating CPU / memory, and how to stop them
keep a job alive after you log out
turn stdin lines into command arguments, safely and in parallel
stop retyping commands
numeric modes decoded + recursive ownership
the daily service-management set
follow, filter by unit and time
the curl invocations that cover 95% of use
is it up, is it reachable, who answers DNS
run something repeatedly — now, or on a schedule
link things, then figure out what they really are
classic one-liners for logs and CSVs
move files between machines with zero setup
the five ffmpeg commands worth memorizing
slice API responses on the command line
where commands come from and how to override them
keep the changes, or destroy them
fix the message or add forgotten files
replay your branch on fresh main; escape hatches included
bring specific commits to this branch
shelve work-in-progress properly
binary search through history, manual or scripted
reflog remembers everything for ~90 days
the modern commands for the two everyday undos
local rename + fix the remote in three commands
land a feature as one clean commit
local, remote, and stale tracking refs
annotated tags for releases
find when, where, and by whom something changed
staged, between branches, word-level, names only
check out another branch in a second directory — no stashing
committed something that belongs in .gitignore
ALWAYS dry-run first
point at the right server; keep a fork fresh
ignore whitespace and code-moves for honest answers
move changes without a shared remote
shallow and partial clones
one-time setup that pays rent daily
the core loop — jobs keep running after you disconnect
all prefixed with C-b (Ctrl+b)
one window per task, numbered from 0
read output that scrolled away
launch and control sessions from shell scripts
interactive, detached, ports, volumes, GPUs
logs, shells, resource usage
the build-and-ship cycle
docker eats disks; prune regularly
multi-container dev environments
in/out of containers; between machines without a registry
small, cache-friendly starting point
FROM python:3.12-slim WORKDIR /app # deps first: this layer caches until requirements.txt changes COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "main.py"]copy
stdlib virtual environments
requirements files and editable installs
create, export, recreate
drop-in, 10–100× faster resolver
make envs visible to Jupyter; run it on a server
stdlib only — no installs needed
the canonical loop: train step, eval step, no surprises
model.train()
for x, y in train_loader:
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
for x, y in val_loader:
preds = model(x.to(device)).argmax(dim=1)copymodern torch.amp autocast + GradScaler
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = model.to(device)
scaler = torch.amp.GradScaler('cuda')
with torch.amp.autocast('cuda'):
loss = criterion(model(x), y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()copythe three methods, then a loader with workers
class MyDataset(torch.utils.data.Dataset):
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
def __getitem__(self, idx):
x, y = self.items[idx]
return torch.tensor(x), torch.tensor(y)
loader = torch.utils.data.DataLoader(
MyDataset(data), batch_size=64, shuffle=True,
num_workers=4, pin_memory=True)copymodel + optimizer + epoch, the resumable way
torch.save({
'epoch': epoch,
'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
}, 'ckpt.pt')
ckpt = torch.load('ckpt.pt', map_location=device)
model.load_state_dict(ckpt['model'])
optimizer.load_state_dict(ckpt['optimizer'])
start_epoch = ckpt['epoch'] + 1copyrequires_grad off for the backbone, train only the head
for p in model.parameters():
p.requires_grad = False
for p in model.fc.parameters(): # unfreeze the head
p.requires_grad = True
optimizer = torch.optim.AdamW(
(p for p in model.parameters() if p.requires_grad), lr=1e-4)copytotal vs trainable, in one line each
the ones you actually reach for; call .step() per epoch
sched = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
sched = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5)
for epoch in range(epochs):
train_one_epoch()
sched.step() # ReduceLROnPlateau: sched.step(val_loss)copypython, numpy, torch, cuda + determinism flags
import random, numpy as np, torch
def seed_everything(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = Falsecopyview vs permute vs einsum — and when view fails
the daily data-wrangling set
nvidia-smi + torch memory tools
train with a big effective batch on a small GPU
accum = 4 # effective batch = 4 × loader batch
optimizer.zero_grad()
for i, (x, y) in enumerate(train_loader):
loss = criterion(model(x), y) / accum
loss.backward()
if (i + 1) % accum == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
optimizer.zero_grad()copypatience counter — no library needed
best, patience, bad_epochs = float('inf'), 10, 0
for epoch in range(max_epochs):
val_loss = validate(model)
if val_loss < best - 1e-4:
best, bad_epochs = val_loss, 0
torch.save(model.state_dict(), 'best.pt')
else:
bad_epochs += 1
if bad_epochs >= patience:
print(f'stopping at epoch {epoch}')
break
model.load_state_dict(torch.load('best.pt'))copypipeline for quick use, Auto* classes for control
from transformers import pipeline
pipe = pipeline('text-generation', model='Qwen/Qwen2.5-0.5B-Instruct')
print(pipe('Hello', max_new_tokens=50)[0]['generated_text'])
# manual control:
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(
name, torch_dtype='auto', device_map='auto')
out = model.generate(**tok(prompt, return_tensors='pt').to(model.device),
max_new_tokens=100)
print(tok.decode(out[0], skip_special_tokens=True))copyvector PDF, right size for a column, readable fonts
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 9, 'pdf.fonttype': 42}) # 42 = editable text
fig, axes = plt.subplots(1, 2, figsize=(6.8, 2.4)) # ~2-column width
for ax, (xs, ys, label) in zip(axes, runs):
ax.plot(xs, ys, label=label)
ax.set_xlabel('Epoch'); ax.grid(alpha=0.3)
axes[0].set_ylabel('Loss'); axes[0].legend(frameon=False)
fig.tight_layout()
fig.savefig('fig/loss.pdf', bbox_inches='tight') # PDF, not PNGcopythe 30-second baseline before anything fancy
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
Xtr, Xte, ytr, yte = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
clf = RandomForestClassifier(n_estimators=300, n_jobs=-1).fit(Xtr, ytr)
print(classification_report(yte, clf.predict(Xte)))
print(confusion_matrix(yte, clf.predict(Xte)))copyCUDA is async — time.time() lies without a sync
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
out = model(x)
end.record()
torch.cuda.synchronize()
print(f'{start.elapsed_time(end):.2f} ms')
# one-line speedup while you're here (PyTorch 2.x):
model = torch.compile(model)copyminimal DistributedDataParallel setup
# launch: torchrun --nproc_per_node=4 train.py
import torch.distributed as dist
dist.init_process_group('nccl')
rank = dist.get_rank()
torch.cuda.set_device(rank)
model = torch.nn.parallel.DistributedDataParallel(
model.cuda(rank), device_ids=[rank])
sampler = torch.utils.data.DistributedSampler(dataset)
loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=64)
for epoch in range(epochs):
sampler.set_epoch(epoch) # reshuffle per epoch
...
dist.destroy_process_group()copyminimal metric logging, both flavors
# TensorBoard (stdlib-adjacent):
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('runs/exp1')
writer.add_scalar('loss/train', loss.item(), step)
# view: tensorboard --logdir runs
# wandb:
import wandb
wandb.init(project='myproj', config={'lr': 1e-4})
wandb.log({'loss': loss.item(), 'epoch': epoch})copythe clean three-rule table every paper uses
% \usepackage{booktabs}
\begin{table}[t]
\centering
\caption{Results on the benchmark.}
\label{tab:results}
\begin{tabular}{lcc}
\toprule
Method & Accuracy & F1 \\
\midrule
Baseline & 84.2 & 0.81 \\
\textbf{Ours} & \textbf{91.7} & \textbf{0.90} \\
\bottomrule
\end{tabular}
\end{table}copyalgpseudocode: the standard pseudo-code environment
% \usepackage{algorithm} \usepackage{algpseudocode}
\begin{algorithm}[t]
\caption{Assertion refinement}\label{alg:refine}
\begin{algorithmic}[1]
\Require design $D$, spec $S$
\State $A \gets \Call{Generate}{D, S}$
\While{$\lnot$ \Call{Verified}{$A, D$}}
\State $A \gets \Call{Refine}{A, \text{counterexample}}$
\EndWhile
\State \Return $A$
\end{algorithmic}
\end{algorithm}copysingle figure and side-by-side subfigures
% \usepackage{graphicx} \usepackage{subcaption}
\begin{figure}[t]
\centering
\begin{subfigure}{0.48\linewidth}
\includegraphics[width=\linewidth]{fig/a.pdf}
\caption{Before}
\end{subfigure}
\hfill
\begin{subfigure}{0.48\linewidth}
\includegraphics[width=\linewidth]{fig/b.pdf}
\caption{After}
\end{subfigure}
\caption{Overall comparison.}\label{fig:comparison}
\end{figure}copyalign at =, number one line, reference it
\begin{align}
\mathcal{L}(\theta) &= \mathbb{E}_{x \sim p}\left[ \log f_\theta(x) \right] \label{eq:loss} \\
\hat{\theta} &= \arg\max_\theta \mathcal{L}(\theta) \nonumber
\end{align}
% inline: as shown in Eq.~\eqref{eq:loss}copypiecewise definitions with the cases environment
f(x) =
\begin{cases}
1 & \text{if } x \geq 0 \\
-1 & \text{otherwise}
\end{cases}copypmatrix (parens), bmatrix (brackets), with dots
A =
\begin{bmatrix}
a_{11} & \cdots & a_{1n} \\
\vdots & \ddots & \vdots \\
a_{m1} & \cdots & a_{mn}
\end{bmatrix},
\quad
v = \begin{pmatrix} x \\ y \end{pmatrix}copyamsthm setup + theorem/lemma/proof
% preamble:
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}
\newtheorem{lemma}[theorem]{Lemma}
\begin{theorem}\label{thm:main}
Every reachable state satisfies $\varphi$.
\end{theorem}
\begin{proof}
By induction on the trace length. \qedhere
\end{proof}copythe two entry types papers need + citing
@inproceedings{paul2025lisa,
author = {Paul, Subhajit and Banerjee, Ansuman},
title = {Title of the Paper},
booktitle = {Proc.\ of CONF},
year = {2025}
}
@article{key2024,
author = {Last, First},
title = {Article Title},
journal = {Journal Name},
year = {2024}
}
% in text: \cite{paul2025lisa} % with natbib: \citep{} \citet{}copya slide with columns and pause-based reveals
\begin{frame}{Frame title}
\begin{columns}
\begin{column}{0.5\textwidth}
\begin{itemize}
\item First point \pause
\item Second point
\end{itemize}
\end{column}
\begin{column}{0.5\textwidth}
\includegraphics[width=\linewidth]{fig/plot.pdf}
\end{column}
\end{columns}
\end{frame}copytwo nodes and an arrow — the seed of every figure
% \usepackage{tikz}
\begin{tikzpicture}[node distance=2.5cm, every node/.style={draw, rounded corners}]
\node (a) {LLM Agent};
\node (b) [right of=a] {Verifier};
\draw[->] (a) -- node[above, draw=none] {\small SVA} (b);
\draw[->] (b) to[bend left] node[below, draw=none] {\small CEX} (a);
\end{tikzpicture}copylatexmk: auto-recompile on save, correct bib passes
the notation every ML/verification paper needs
stop typing "Figure~\ref{...}" by hand
legal(ish) tricks for the page limit
cells spanning rows/columns
IEEEtran: the start of every submission
\documentclass[conference]{IEEEtran}
\usepackage{graphicx,booktabs,amsmath,amssymb}
\usepackage[capitalize]{cleveref}
\title{Paper Title}
\author{\IEEEauthorblockN{Subhajit Paul}
\IEEEauthorblockA{Indian Statistical Institute, Kolkata \\
paul@isical.ac.in}}
\begin{document}
\maketitle
\begin{abstract}...\end{abstract}
\section{Introduction}
\bibliographystyle{IEEEtran}
\bibliography{refs}
\end{document}copy