Skip to content

Bioinformatics & structural biology

Scientific computing in genomics, cheminformatics, and structural biology is full of kernels that do not fit standard dense GEMM libraries: byte-level FASTQ parsing and 2-bit k-mer packing, multi-channel alignment pileups, 2048-bit chemical fingerprint screening, 3D protein coordinate message passing, and banded dynamic programming alignments.

Parakeet compiles these workloads directly from concise NumPy and data-parallel operators into fused, multi-core CPU and GPU code — without hand-writing C, CUDA, or Metal.

Every snippet below is included from examples/bio_gallery.py. Run the gallery checks or reproducible benchmarks from a source checkout:

python -m examples.bio_gallery
python benchmarks/bio_workloads.py

How algebraic primitives map to bio workloads

Domain task Operator / optimization in Parakeet What the compiler eliminates
FASTQ k-mers & read QC par.parfor + uint8 / uint64 bitwise arithmetic Python per-character loops and string copies
Multi-channel BAM pileup Keyed IndexScatter fusion Redundant passes over alignment positions (6 -> 1)
Chemical fingerprint screening par.allpairs + ordered par.fold (pairwise_fold) O(N · M) similarity matrix allocation
3D protein RBF / equivariant attention Online rescaled-monoid tiling + par.grad O(N²) pairwise distance & weight matrices
Banded Smith-Waterman & genome SSMs Two-row banded DP + chunkwise affine prefix scan (TileScan) Python DP interpreter overhead & sequential scan bottlenecks

1. FASTQ 2-bit canonical k-mers and read QC

Representing raw DNA and Phred quality bytes as uint8 arrays lets Parakeet compute forward and reverse-complement 2-bit uint64 canonical k-mers (min(fwd, revcomp)), GC fraction, and mean Phred quality in one parallel pass over reads:

@par.jit
def encode_canonical_kmers_and_gc(seq_bytes, qual_bytes, k):
  """Encode a batch of equal-length ASCII DNA reads (N, L) uint8 into:
  - canonical 2-bit k-mers (N, L - k + 1) uint64  [min(fwd, revcomp)]
  - per-read GC fraction (N,) float32
  - per-read mean Phred quality (N,) float32
  """
  n_reads, read_len = seq_bytes.shape
  n_kmers = read_len - k + 1
  kmers = np.empty((n_reads, n_kmers), dtype=np.uint64)
  gc_frac = np.empty((n_reads,), dtype=np.float32)
  mean_q = np.empty((n_reads,), dtype=np.float32)
  mask = (~np.uint64(0)) >> np.uint64(64 - 2 * k)
  rev_shift = np.uint64(2 * (k - 1))

  def process_read(r):
    gc = np.int64(0)
    qsum = np.int64(0)
    fwd = np.uint64(0)
    rev = np.uint64(0)
    for pos in range(read_len):
      ch = seq_bytes[r, pos]
      # ASCII: A=65 -> 0, C=67 -> 1, G=71 -> 2, T=84 -> 3
      is_c = ch == np.uint8(67)
      is_g = ch == np.uint8(71)
      is_t = ch == np.uint8(84)
      code = np.uint64(1) if is_c else (np.uint64(2) if is_g else (np.uint64(3) if is_t else np.uint64(0)))
      comp = np.uint64(3) ^ code
      if is_c or is_g:
        gc = gc + np.int64(1)
      qsum = qsum + np.int64(qual_bytes[r, pos]) - np.int64(33)
      fwd = ((fwd << np.uint64(2)) | code) & mask
      rev = (rev >> np.uint64(2)) | (comp << rev_shift)
      if pos >= k - 1:
        kmers[r, pos - k + 1] = fwd if fwd < rev else rev
    gc_frac[r] = np.float32(gc) / np.float32(read_len)
    mean_q[r] = np.float32(qsum) / np.float32(read_len)

  par.parfor(process_read, n_reads)
  return kmers, gc_frac, mean_q

2. Single-pass multi-channel alignment pileup

A pileup records A/C/G/T base counts, Phred quality sums, and reverse-strand counts at each reference coordinate. Because all six par.scatter_add updates share the same index array ref_pos, Parakeet's scatter-fusion pass combines them into a single privatized traversal (IndexScatter: 6 -> 1):

@par.jit
def single_pass_pileup(ref_pos, base_code, phred_q, is_rev, contig_len):
  """Accumulate A/C/G/T counts, quality sums, and reverse-strand counts across
  aligned base observations in one keyed IndexScatter traversal."""
  is_a = (base_code == np.uint8(0)).astype(np.int64)
  is_c = (base_code == np.uint8(1)).astype(np.int64)
  is_g = (base_code == np.uint8(2)).astype(np.int64)
  is_t = (base_code == np.uint8(3)).astype(np.int64)
  q_i64 = phred_q.astype(np.int64)
  rev_i64 = is_rev.astype(np.int64)

  # All six histograms share `ref_pos` -> Parakeet fuses them into ONE traversal!
  cnt_a = par.scatter_add(contig_len, ref_pos, is_a)
  cnt_c = par.scatter_add(contig_len, ref_pos, is_c)
  cnt_g = par.scatter_add(contig_len, ref_pos, is_g)
  cnt_t = par.scatter_add(contig_len, ref_pos, is_t)
  qual_sum = par.scatter_add(contig_len, ref_pos, q_i64)
  rev_cnt = par.scatter_add(contig_len, ref_pos, rev_i64)
  return cnt_a, cnt_c, cnt_g, cnt_t, qual_sum, rev_cnt

3. 2048-bit Morgan fingerprint Tanimoto screening

Chemical similarity screening compares query fingerprints (N, 32) against a compound library (M, 32) of packed uint64 bitvectors (2,048 bits each). Combining a portable 64-bit SWAR popcount with par.allpairs and an ordered par.fold finds the closest library compound per query while preserving first-index ties:

def popcount64(x):
  """Branchless 64-bit SWAR popcount (portable across C, multicore, Metal, CUDA)."""
  u = x - ((x >> np.uint64(1)) & np.uint64(0x5555555555555555))
  u = (u & np.uint64(0x3333333333333333)) + ((u >> np.uint64(2)) & np.uint64(0x3333333333333333))
  u = (u + (u >> np.uint64(4))) & np.uint64(0x0F0F0F0F0F0F0F0F)
  return (u * np.uint64(0x0101010101010101)) >> np.uint64(56)


class BestHit(NamedTuple):
  sim: np.float32
  index: np.int64


def better_hit(left, right):
  # Highest Tanimoto similarity wins; ties preserve the first library compound.
  return right if right.sim > left.sim else left


@par.jit
def tanimoto_nearest_hit(queries, library):
  """Find the closest library compound per query over packed uint64 fingerprints
  (N, W) x (M, W) using tiled pairwise folds with zero N x M allocation."""
  pop_q = np.sum(popcount64(queries), axis=1)
  pop_l = np.sum(popcount64(library), axis=1)

  def inter_bits(q_row, l_row):
    return np.sum(popcount64(q_row & l_row))

  # Stream intersection counts into an ordered fold over library compounds
  inter = par.allpairs(inter_bits, queries, library)
  denom = pop_q[:, None] + pop_l[None, :] - inter
  sim = np.where(
    denom > np.uint64(0), inter.astype(np.float32) / np.maximum(denom, np.uint64(1)).astype(np.float32), np.float32(0.0)
  )
  return par.fold(
    lambda score, ref_idx: BestHit(score, ref_idx),
    better_hit,
    sim,
    axis=1,
    indexed=True,
    emit=lambda hit: hit.index,
  )

4. 3D protein coordinate RBF message passing

Pairwise radial-basis-function smoothing over 3D residue coordinates (N, 3) uses the same rescaled-monoid structure as softmax attention. Online monoidal tiling fuses the squared-distance computation, softmax normalization, and feature aggregation into a single tiled pass with zero O(N²) score allocation — and par.grad differentiates through the 3D coordinates directly:

@par.jit
def protein_rbf_message_passing(coords, features, neg_inv_2sigma2):
  """3D radial-basis-function message passing over residue coordinates (N, 3).

  Fuses into online (m, l, O) monoidal tiles with zero N x N materialization.
  """
  d2 = np.sum((coords[:, None, :] - coords[None, :, :]) ** np.float32(2.0), axis=-1)
  s = d2 * neg_inv_2sigma2
  e = np.exp(s - np.max(s, axis=-1, keepdims=True))
  return (e / np.sum(e, axis=-1, keepdims=True)) @ features


def protein_rbf_loss(coords, features, targets, neg_inv_2sigma2):
  pred = protein_rbf_message_passing(coords, features, neg_inv_2sigma2)
  diff = pred - targets
  return np.mean(diff * diff)


protein_coord_grad = par.grad(protein_rbf_loss, argnum=0)

5. Banded Smith-Waterman alignment and DNA state-space scan

Compiled two-row banded Smith-Waterman keeps only O(M) score scratch in L1 cache, while 1D DNA exponential state-space recurrences automatically rewrite into chunkwise parallel affine prefix scans (TileScan):

@par.jit
def banded_smith_waterman(seq_a, seq_b, match_score, mismatch_pen, gap_pen, band_width):
  """Banded Smith-Waterman local alignment score over integer-encoded sequences.

  Keeps only two O(M) score rows in cache and restricts columns to |j - i| <= band_width.
  """
  n = seq_a.shape[0]
  m = seq_b.shape[0]
  prev = np.zeros((m + 1,), dtype=np.float32)
  curr = np.zeros((m + 1,), dtype=np.float32)
  best = np.float32(0.0)
  for i in range(1, n + 1):
    ai = seq_a[i - 1]
    j_lo = i - band_width
    if j_lo < 1:
      j_lo = 1
    j_hi = i + band_width
    if j_hi > m:
      j_hi = m
    for j in range(j_lo, j_hi + 1):
      sub = match_score if ai == seq_b[j - 1] else mismatch_pen
      v = prev[j - 1] + sub
      up = prev[j] + gap_pen
      left = curr[j - 1] + gap_pen
      if up > v:
        v = up
      if left > v:
        v = left
      if v < np.float32(0.0):
        v = np.float32(0.0)
      curr[j] = v
      if v > best:
        best = v
    for j in range(j_lo, j_hi + 1):
      prev[j] = curr[j]
      curr[j] = np.float32(0.0)
  return best


@par.jit
def dna_ssm_scan(decay, signal):
  """Exponential state-space scan along a DNA track (L,).

  Compiled via chunkwise parallel affine prefix scan (TileScan).
  """
  length = decay.shape[0]
  out = np.empty_like(signal)
  s = np.float32(0.0)
  for t in range(length):
    s = decay[t] * s + signal[t]
    out[t] = s
  return out

Inspecting the rewrites

Run par.show_rewrite on any workload above to verify that scatter fusion, online monoidal tiling, or chunkwise parallel scans fired:

import numpy as np
import parakeet as par
from examples.bio_gallery import single_pass_pileup, protein_rbf_message_passing

pos = np.zeros(10_000, np.int64)
u8 = np.zeros(10_000, np.uint8)
print(par.show_rewrite(single_pass_pileup, pos, u8, u8, u8, 4096).summary())

coords = np.zeros((128, 3), np.float32)
feats = np.zeros((128, 16), np.float32)
print(par.show_rewrite(protein_rbf_message_passing, coords, feats, np.float32(-0.05)).summary())