callbacks.py 2.2 KB

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