callbacks.py 2.7 KB

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