callbacks.py 2.7 KB

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