callbacks.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from queue import Queue
  2. from threading import Thread
  3. import torch
  4. import transformers
  5. from modules.text_generation import clear_torch_cache
  6. # Copied from https://github.com/PygmalionAI/gradio-ui/
  7. class _SentinelTokenStoppingCriteria(transformers.StoppingCriteria):
  8. def __init__(self, sentinel_token_ids: list[torch.LongTensor], starting_idx: int):
  9. transformers.StoppingCriteria.__init__(self)
  10. self.sentinel_token_ids = sentinel_token_ids
  11. self.starting_idx = starting_idx
  12. def __call__(self, input_ids: torch.LongTensor, _scores: torch.FloatTensor) -> bool:
  13. for sample in input_ids:
  14. trimmed_sample = sample[self.starting_idx:]
  15. for i in range(len(self.sentinel_token_ids)):
  16. # Can't unfold, output is still too tiny. Skip.
  17. if trimmed_sample.shape[-1] < self.sentinel_token_ids[i].shape[-1]:
  18. continue
  19. for window in trimmed_sample.unfold(0, self.sentinel_token_ids[i].shape[-1], 1):
  20. if torch.all(torch.eq(self.sentinel_token_ids[i], window)):
  21. return True
  22. return False
  23. class Stream(transformers.StoppingCriteria):
  24. def __init__(self, callback_func=None):
  25. self.callback_func = callback_func
  26. def __call__(self, input_ids, scores) -> bool:
  27. if self.callback_func is not None:
  28. self.callback_func(input_ids[0])
  29. return False
  30. class Iteratorize:
  31. """
  32. Transforms a function that takes a callback
  33. into a lazy iterator (generator).
  34. """
  35. def __init__(self, func, kwargs={}, callback=None):
  36. self.mfunc=func
  37. self.c_callback=callback
  38. self.q = Queue()
  39. self.sentinel = object()
  40. self.kwargs = kwargs
  41. self.stop_now = False
  42. def _callback(val):
  43. if self.stop_now:
  44. raise ValueError
  45. self.q.put(val)
  46. def gentask():
  47. try:
  48. ret = self.mfunc(callback=_callback, **self.kwargs)
  49. except ValueError:
  50. pass
  51. clear_torch_cache()
  52. self.q.put(self.sentinel)
  53. if self.c_callback:
  54. self.c_callback(ret)
  55. self.thread = Thread(target=gentask)
  56. self.thread.start()
  57. def __iter__(self):
  58. return self
  59. def __next__(self):
  60. obj = self.q.get(True,None)
  61. if obj is self.sentinel:
  62. raise StopIteration
  63. else:
  64. return obj
  65. def __del__(self):
  66. clear_torch_cache()
  67. def __enter__(self):
  68. return self
  69. def __exit__(self, exc_type, exc_val, exc_tb):
  70. self.stop_now = True
  71. clear_torch_cache()