RWKV.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. import time
  3. import types
  4. from pathlib import Path
  5. import numpy as np
  6. import torch
  7. import modules.shared as shared
  8. np.set_printoptions(precision=4, suppress=True, linewidth=200)
  9. os.environ['RWKV_JIT_ON'] = '1'
  10. os.environ["RWKV_CUDA_ON"] = '0' # '1' : use CUDA kernel for seq mode (much faster)
  11. from rwkv.model import RWKV
  12. from rwkv.utils import PIPELINE, PIPELINE_ARGS
  13. class RWKVModel:
  14. def __init__(self):
  15. pass
  16. @classmethod
  17. def from_pretrained(self, path, dtype="fp16", device="cuda"):
  18. tokenizer_path = Path(f"{path.parent}/20B_tokenizer.json")
  19. model = RWKV(model=os.path.abspath(path), strategy=f'{device} {dtype}')
  20. pipeline = PIPELINE(model, os.path.abspath(tokenizer_path))
  21. result = self()
  22. result.pipeline = pipeline
  23. return result
  24. def generate(self, context, token_count=20, temperature=1, top_p=1, alpha_frequency=0.25, alpha_presence=0.25, token_ban=[0], token_stop=[], callback=None):
  25. args = PIPELINE_ARGS(
  26. temperature = temperature,
  27. top_p = top_p,
  28. alpha_frequency = alpha_frequency, # Frequency Penalty (as in GPT-3)
  29. alpha_presence = alpha_presence, # Presence Penalty (as in GPT-3)
  30. token_ban = token_ban, # ban the generation of some tokens
  31. token_stop = token_stop
  32. )
  33. return context+self.pipeline.generate(context, token_count=token_count, args=args, callback=callback)