template.tpl 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import torch
  3. from modelscope.models.base import TorchModel
  4. from modelscope.preprocessors.base import Preprocessor
  5. from modelscope.pipelines.base import Model, Pipeline
  6. from modelscope.utils.config import Config
  7. from modelscope.pipelines.builder import PIPELINES
  8. from modelscope.preprocessors.builder import PREPROCESSORS
  9. from modelscope.models.builder import MODELS
  10. @MODELS.register_module('${task_name}', module_name='my-custom-model')
  11. class ${model_name}(TorchModel):
  12. def __init__(self, model_dir, *args, **kwargs):
  13. super().__init__(model_dir, *args, **kwargs)
  14. self.model = self.init_model(**kwargs)
  15. def forward(self, input_tensor, **forward_params):
  16. return self.model(input_tensor, **forward_params)
  17. def init_model(self, **kwargs):
  18. """Provide default implementation based on TorchModel and user can reimplement it.
  19. include init model and load ckpt from the model_dir, maybe include preprocessor
  20. if nothing to do, then return lambda x: x
  21. """
  22. return lambda x: x
  23. @PREPROCESSORS.register_module('${task_name}', module_name='my-custom-preprocessor')
  24. class ${preprocessor_name}(Preprocessor):
  25. def __init__(self, *args, **kwargs):
  26. super().__init__(*args, **kwargs)
  27. self.trainsforms = self.init_preprocessor(**kwargs)
  28. def __call__(self, results):
  29. return self.trainsforms(results)
  30. def init_preprocessor(self, **kwarg):
  31. """ Provide default implementation based on preprocess_cfg and user can reimplement it.
  32. if nothing to do, then return lambda x: x
  33. """
  34. return lambda x: x
  35. @PIPELINES.register_module('${task_name}', module_name='my-custom-pipeline')
  36. class ${pipeline_name}(Pipeline):
  37. """ Give simple introduction to this pipeline.
  38. Examples:
  39. >>> from modelscope.pipelines import pipeline
  40. >>> input = "Hello, ModelScope!"
  41. >>> my_pipeline = pipeline('my-task', 'my-model-id')
  42. >>> result = my_pipeline(input)
  43. """
  44. def __init__(self, model, preprocessor=None, **kwargs):
  45. """
  46. use `model` and `preprocessor` to create a custom pipeline for prediction
  47. Args:
  48. model: model id on modelscope hub.
  49. preprocessor: the class of method be init_preprocessor
  50. """
  51. super().__init__(model=model, auto_collate=False)
  52. assert isinstance(model, str) or isinstance(model, Model), \
  53. 'model must be a single str or Model'
  54. if isinstance(model, str):
  55. pipe_model = Model.from_pretrained(model)
  56. elif isinstance(model, Model):
  57. pipe_model = model
  58. else:
  59. raise NotImplementedError
  60. pipe_model.eval()
  61. if preprocessor is None:
  62. preprocessor = ${preprocessor_name}()
  63. super().__init__(model=pipe_model, preprocessor=preprocessor, **kwargs)
  64. def _sanitize_parameters(self, **pipeline_parameters):
  65. """
  66. this method should sanitize the keyword args to preprocessor params,
  67. forward params and postprocess params on '__call__' or '_process_single' method
  68. considered to be a normal classmethod with default implementation / output
  69. Default Returns:
  70. Dict[str, str]: preprocess_params = {}
  71. Dict[str, str]: forward_params = {}
  72. Dict[str, str]: postprocess_params = pipeline_parameters
  73. """
  74. return {}, pipeline_parameters, {}
  75. def _check_input(self, inputs):
  76. pass
  77. def _check_output(self, outputs):
  78. pass
  79. def forward(self, inputs, **forward_params):
  80. """ Provide default implementation using self.model and user can reimplement it
  81. """
  82. return super().forward(inputs, **forward_params)
  83. def postprocess(self, inputs):
  84. """ If current pipeline support model reuse, common postprocess
  85. code should be write here.
  86. Args:
  87. inputs: input data
  88. Return:
  89. dict of results: a dict containing outputs of model, each
  90. output should have the standard output name.
  91. """
  92. return inputs
  93. # Tips: usr_config_path is the temporary save configuration location, after upload modelscope hub, it is the model_id
  94. usr_config_path = '${configuration_path}'
  95. config = Config({
  96. "framework": 'pytorch',
  97. "task": '${task_name}',
  98. "model": {'type': 'my-custom-model'},
  99. "pipeline": {"type": "my-custom-pipeline"},
  100. "allow_remote": True
  101. })
  102. config.dump('${configuration_path}' + 'configuration.json')
  103. if __name__ == "__main__":
  104. from modelscope.models import Model
  105. from modelscope.pipelines import pipeline
  106. # model = Model.from_pretrained(usr_config_path)
  107. input = "Hello, ModelScope!"
  108. inference = pipeline('${task_name}', model=usr_config_path)
  109. output = inference(input)
  110. print(output)