RWKV.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. from pathlib import Path
  3. import numpy as np
  4. import modules.shared as shared
  5. np.set_printoptions(precision=4, suppress=True, linewidth=200)
  6. os.environ['RWKV_JIT_ON'] = '1'
  7. os.environ["RWKV_CUDA_ON"] = '0' # '1' : use CUDA kernel for seq mode (much faster)
  8. from rwkv.model import RWKV
  9. from rwkv.utils import PIPELINE, PIPELINE_ARGS
  10. class RWKVModel:
  11. def __init__(self):
  12. pass
  13. @classmethod
  14. def from_pretrained(self, path, dtype="fp16", device="cuda"):
  15. tokenizer_path = Path(f"{path.parent}/20B_tokenizer.json")
  16. if shared.args.rwkv_strategy is None:
  17. model = RWKV(model=os.path.abspath(path), strategy=f'{device} {dtype}')
  18. else:
  19. model = RWKV(model=os.path.abspath(path), strategy=shared.args.rwkv_strategy)
  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)