RWKV.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. from pathlib import Path
  3. import numpy as np
  4. from tokenizers import Tokenizer
  5. import modules.shared as shared
  6. np.set_printoptions(precision=4, suppress=True, linewidth=200)
  7. os.environ['RWKV_JIT_ON'] = '1'
  8. os.environ["RWKV_CUDA_ON"] = '0' # '1' : use CUDA kernel for seq mode (much faster)
  9. from rwkv.model import RWKV
  10. from rwkv.utils import PIPELINE, PIPELINE_ARGS
  11. class RWKVModel:
  12. def __init__(self):
  13. pass
  14. @classmethod
  15. def from_pretrained(self, path, dtype="fp16", device="cuda"):
  16. tokenizer_path = Path(f"{path.parent}/20B_tokenizer.json")
  17. if shared.args.rwkv_strategy is None:
  18. model = RWKV(model=os.path.abspath(path), strategy=f'{device} {dtype}')
  19. else:
  20. model = RWKV(model=os.path.abspath(path), strategy=shared.args.rwkv_strategy)
  21. pipeline = PIPELINE(model, os.path.abspath(tokenizer_path))
  22. result = self()
  23. result.pipeline = pipeline
  24. return result
  25. 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):
  26. args = PIPELINE_ARGS(
  27. temperature = temperature,
  28. top_p = top_p,
  29. alpha_frequency = alpha_frequency, # Frequency Penalty (as in GPT-3)
  30. alpha_presence = alpha_presence, # Presence Penalty (as in GPT-3)
  31. token_ban = token_ban, # ban the generation of some tokens
  32. token_stop = token_stop
  33. )
  34. return context+self.pipeline.generate(context, token_count=token_count, args=args, callback=callback)
  35. class RWKVTokenizer:
  36. def __init__(self):
  37. pass
  38. @classmethod
  39. def from_pretrained(self, path):
  40. tokenizer_path = path / "20B_tokenizer.json"
  41. tokenizer = Tokenizer.from_file(os.path.abspath(tokenizer_path))
  42. result = self()
  43. result.tokenizer = tokenizer
  44. return result
  45. def encode(self, prompt):
  46. return self.tokenizer.encode(prompt).ids
  47. def decode(self, ids):
  48. return self.tokenizer.decode(ids)