|
| 1 | +import pytest |
| 2 | +import torch |
| 3 | +from transformers import AutoTokenizer |
| 4 | + |
| 5 | +from outlines.serve.vllm import ( |
| 6 | + CFGLogitsProcessor, |
| 7 | + JSONLogitsProcessor, |
| 8 | + RegexLogitsProcessor, |
| 9 | +) |
| 10 | + |
| 11 | +TEST_REGEX = r"(-)?(0|[1-9][0-9]*)(.[0-9]+)?([eE][+-][0-9]+)?" |
| 12 | +TEST_CFG = """ |
| 13 | +start: DECIMAL |
| 14 | +DIGIT: "0".."9" |
| 15 | +INT: DIGIT+ |
| 16 | +DECIMAL: INT "." INT? | "." INT |
| 17 | +""" |
| 18 | +TEST_SCHEMA = '{"type": "string", "maxLength": 5}' |
| 19 | + |
| 20 | +LOGIT_PROCESSORS = ( |
| 21 | + (CFGLogitsProcessor, TEST_CFG), |
| 22 | + (RegexLogitsProcessor, TEST_REGEX), |
| 23 | + (JSONLogitsProcessor, TEST_SCHEMA), |
| 24 | +) |
| 25 | + |
| 26 | +TEST_MODEL = "hf-internal-testing/tiny-random-GPTJForCausalLM" |
| 27 | + |
| 28 | + |
| 29 | +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires cuda available") |
| 30 | +@pytest.mark.parametrize("logit_processor, fsm_str", LOGIT_PROCESSORS) |
| 31 | +def test_logit_processor(logit_processor, fsm_str: str): |
| 32 | + class MockvLLMEngine: |
| 33 | + def __init__(self, tokenizer): |
| 34 | + self.tokenizer = tokenizer |
| 35 | + |
| 36 | + def __call__(*_): |
| 37 | + return torch.tensor([[0, 1, 2, 3, 4]], dtype=torch.float), None |
| 38 | + |
| 39 | + tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL) |
| 40 | + engine = MockvLLMEngine(tokenizer) |
| 41 | + logit_processor(fsm_str, engine) |
| 42 | + assert isinstance(engine.tokenizer.decode([0, 1, 2, 3]), list) |
| 43 | + logit_processor(fsm_str, engine) |
| 44 | + assert isinstance(engine.tokenizer.decode([0, 1, 2, 3]), list) |
0 commit comments