callbacks.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. Helpers to support streaming generate output.
  3. Borrowed from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/callbacks.py
  4. """
  5. import gc
  6. import traceback
  7. from queue import Queue
  8. from threading import Thread
  9. import torch
  10. import transformers
  11. class Stream(transformers.StoppingCriteria):
  12. def __init__(self, callback_func=None):
  13. self.callback_func = callback_func
  14. def __call__(self, input_ids, scores) -> bool:
  15. if self.callback_func is not None:
  16. self.callback_func(input_ids[0])
  17. return False
  18. class Iteratorize:
  19. """
  20. Transforms a function that takes a callback
  21. into a lazy iterator (generator).
  22. """
  23. def __init__(self, func, kwargs={}, callback=None):
  24. self.mfunc = func
  25. self.c_callback = callback
  26. self.q = Queue()
  27. self.sentinel = object()
  28. self.kwargs = kwargs
  29. self.stop_now = False
  30. def _callback(val):
  31. if self.stop_now:
  32. raise ValueError
  33. self.q.put(val)
  34. def gentask():
  35. try:
  36. ret = self.mfunc(callback=_callback, **self.kwargs)
  37. except ValueError:
  38. pass
  39. except:
  40. traceback.print_exc()
  41. pass
  42. self.q.put(self.sentinel)
  43. if self.c_callback:
  44. self.c_callback(ret)
  45. self.thread = Thread(target=gentask)
  46. self.thread.start()
  47. def __iter__(self):
  48. return self
  49. def __next__(self):
  50. obj = self.q.get(True, None)
  51. if obj is self.sentinel:
  52. raise StopIteration
  53. else:
  54. return obj
  55. def __enter__(self):
  56. return self
  57. def __exit__(self, exc_type, exc_val, exc_tb):
  58. self.stop_now = True