Skip to content

Instantly share code, notes, and snippets.

@vsemionov
vsemionov / pytorch_sample.py
Created May 8, 2024 09:03
Sampling for autoregressive models in PyTorch.
import torch
@torch.no_grad()
def sample(model, x, output_length, block_size, exclude_classes=None, temperature=1, top_k=None, top_p=None):
"""
Sampling for autoregressive models in PyTorch.
See `How to generate text <https://huggingface.co/blog/how-to-generate>`_.
Args:
@vsemionov
vsemionov / transformer.py
Last active May 10, 2024 22:12
Transformer model in PyTorch
# references:
# https://peterbloem.nl/blog/transformers
# https://github.com/karpathy/minGPT
# https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/transformer.py
import math
import torch
import torch.nn as nn
@vsemionov
vsemionov / pytorch_beam_search.py
Last active May 8, 2024 07:06
Beam search for PyTorch
import torch
@torch.no_grad()
def beam_search(model, x, beam_width, output_length, block_size=None, exclude_classes=None, temperature=1):
"""
Beam search for PyTorch.
See `Beam search <https://en.wikipedia.org/wiki/Beam_search>`_.
Args:
@vsemionov
vsemionov / cron.py
Created February 7, 2024 04:55
Cron in one screenful of Python
#!/usr/bin/env python
import os
import sys
import time
from crontab import CronTab
def main():