Skip to main content

An easy-to-use LLM controllable generation tool

Project description

FlexyGen

English | 中文版

FlexyGen is an easy-to-use LLM controllable generation tool that controls and adjusts model generation content by injecting triggers and invocations into the model.

Getting Started

Demo Code: examples/emoji.py

0. Import Dependencies

import random

from typing import List
from transformers import (
    AutoTokenizer,
    AutoModelForCausalLM,
    BitsAndBytesConfig,
)
from flexygen import Insertable

1. Load HF Tokenizer and Model

tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B")
model = AutoModelForCausalLM.from_pretrained(
    "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
    quantization_config=BitsAndBytesConfig(load_in_4bit=True),
)

2. Wrap the Model with FlexyGen Interface

The Insertable interface can be used to insert content into the sentence being generated when certain conditions are met.

model = Insertable.wrap(model, tokenizer)

3. Inject a Trigger

Inject a trigger named emoji into the model.

During the model generation process, the trigger is called every time a token is generated, and an invocation is triggered when the trigger returns True.

Here input_ids is the content currently generated by the model.

@model.trigger("emoji")
def emoji_trigger(input_ids) -> bool:
    sentence = tokenizer.batch_decode(input_ids)[0].strip()
    return sentence.endswith((".", "!", "?"))

4. Inject an Invocation

Injects an invocation named emoji.

This invocation is triggered when the trigger of the same name returns True.

The string returned by the call is inserted after the currently generated content (Currently only batch_size=1 supported).

@model.invocation("emoji")
def generate_random_emoji(input_ids) -> List[str]:
    def random_emoji():
        ranges = [
            (0x1F600, 0x1F64F),
            (0x1F300, 0x1F5FF),
            (0x1F680, 0x1F6FF),
            (0x2700, 0x27BF),
        ]
        start, end = random.choice(ranges)
        code_point = random.randint(start, end)
        return chr(code_point)
    bsz = input_ids.size(0)
    return [random_emoji() for _ in range(bsz)]

5. Generate

input_text = tokenizer.apply_chat_template([
    {"role": "user", "content": "Why the sky is blue?"},
], tokenize=False)
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, do_sample=True, max_new_tokens=128)
# Emoji attached after each sentence.
print(tokenizer.batch_decode(outputs)[0])

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flexygen-0.0.1.tar.gz (20.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flexygen-0.0.1-py3-none-any.whl (21.5 kB view details)

Uploaded Python 3

File details

Details for the file flexygen-0.0.1.tar.gz.

File metadata

  • Download URL: flexygen-0.0.1.tar.gz
  • Upload date:
  • Size: 20.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.2

File hashes

Hashes for flexygen-0.0.1.tar.gz
Algorithm Hash digest
SHA256 b019f71aa38e8a771fe7d9f9dab966095e0e3aa46f29d51b85f810ec721356f3
MD5 69329a04d36b4fab6d5fdbf177dec9b0
BLAKE2b-256 2c23874d54aa527865b28b65f3b88b612cf4600033fefa7ab229856b3c50cfcf

See more details on using hashes here.

File details

Details for the file flexygen-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: flexygen-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 21.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.2

File hashes

Hashes for flexygen-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6409f039eda097531b42c16a9b4c8cad6ff32f7091bbc120ef3e4e8bc7d35b96
MD5 c8e1fc1d37dadef935b8e4878b6ce5e1
BLAKE2b-256 75732c003ddacebc2ca6fac17cf2c96e5cabcf10bd7efab8a891592398c75346

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page