Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

inference.py 5.3 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
  1. import io
  2. from abc import ABC, abstractmethod
  3. from pathlib import Path
  4. from typing import Union
  5. import numpy as np
  6. import torch
  7. from deadtrees.data.deadtreedata import val_transform
  8. from deadtrees.network.segmodel import SemSegment
  9. from matplotlib import cm
  10. from PIL import Image
  11. class Inference(ABC):
  12. def __init__(self, model_file: Union[str, Path]) -> None:
  13. self._model_file = (
  14. model_file if isinstance(model_file, Path) else Path(model_file)
  15. )
  16. super().__init__()
  17. @property
  18. def model_file(self) -> str:
  19. return self._model_file.name
  20. @abstractmethod
  21. def run(self, input_tensor: torch.Tensor):
  22. pass
  23. class PyTorchInference(Inference):
  24. def __init__(self, model_file) -> None:
  25. super().__init__(model_file)
  26. if self._model_file.suffix != ".ckpt":
  27. raise ValueError(
  28. f"ckpt file expected, but {self._model_file.suffix} received"
  29. )
  30. model = SemSegment.load_from_checkpoint(self._model_file)
  31. model.eval()
  32. self._channels = list(model.parameters())[0].shape[1]
  33. # TODO: this is ugly, rename or restructure
  34. self._model = model.model
  35. def run(self, input_tensor, device: str = "cpu"):
  36. if not isinstance(input_tensor, torch.Tensor):
  37. raise TypeError("no pytorch tensor provided")
  38. self._model.to(device)
  39. if input_tensor.dim() == 3:
  40. input_tensor.unsqueeze_(0)
  41. with torch.no_grad():
  42. if (self._channels == 3) and (input_tensor.shape[1] == 4):
  43. # rgb model but rgbn data
  44. input_tensor = input_tensor[:, 0:3, :, :]
  45. out = self._model(input_tensor)
  46. return out.argmax(dim=1).squeeze()
  47. class PyTorchEnsembleInference:
  48. def __init__(self, *model_files: Path):
  49. self._models = []
  50. self._channels = None
  51. if len(model_files) % 2 == 0:
  52. raise ValueError(
  53. "PyTorchEnsembleInference requires an uneven number of models"
  54. )
  55. for model_file in model_files:
  56. if model_file.suffix != ".ckpt":
  57. raise ValueError(
  58. f"Ckpt file expected, but {model_file.suffix} received"
  59. )
  60. model = SemSegment.load_from_checkpoint(model_file)
  61. model.eval()
  62. channels = list(model.parameters())[0].shape[1]
  63. if not self._channels:
  64. self._channels = channels
  65. if channels != self._channels:
  66. raise ValueError(
  67. "Models are not compatible since they were trained for different channel configs"
  68. )
  69. # TODO: this is ugly, rename or restructure
  70. self._models.append(model.model)
  71. def run(self, input_tensor, device: str = "cpu"):
  72. if not isinstance(input_tensor, torch.Tensor):
  73. raise TypeError("No PyTorch tensor provided")
  74. if input_tensor.dim() == 3:
  75. input_tensor.unsqueeze_(0)
  76. if (self._channels == 3) and (input_tensor.shape[1] == 4):
  77. # rgb model but rgbn data
  78. input_tensor = input_tensor[:, 0:3, :, :]
  79. outs = []
  80. for model in self._models:
  81. model.to(device)
  82. with torch.no_grad():
  83. out = model(input_tensor)
  84. outs.append(out.argmax(dim=1).squeeze())
  85. return torch.mode(torch.stack(outs, dim=1), axis=1)[0]
  86. class ONNXInference(Inference):
  87. def __init__(self, model_file) -> None:
  88. super().__init__(model_file)
  89. if self._model_file.suffix != ".onnx":
  90. raise ValueError(
  91. f"onnx file expected, but {self._model_file.suffix} received"
  92. )
  93. import onnxruntime
  94. self._sess = onnxruntime.InferenceSession(str(self._model_file), None)
  95. def run(self, input_array):
  96. if not isinstance(input_array, np.ndarray):
  97. raise TypeError("no numpy array provided")
  98. if input_array.ndim == 3:
  99. input_array = input_array[np.newaxis, ...]
  100. input_name = self._sess.get_inputs()[0].name
  101. output_name = self._sess.get_outputs()[0].name
  102. out = self._sess.run([output_name], {input_name: input_array})[0]
  103. return np.argmax(out, axis=1).squeeze()
  104. # def get_model(model_path: str = "bestmodel.ckpt"):
  105. # model = SemSegment.load_from_checkpoint(model_path)
  106. # model.eval()
  107. # return model
  108. def split_image_into_tiles(image: Image):
  109. # complete this: what about batches?
  110. batch = val_transform(image=image)["image"]
  111. return batch.unsqueeze(0)
  112. def get_segmentation(
  113. model: SemSegment, binary_image: bytes, model_name: str = "unknown"
  114. ):
  115. image = Image.open(io.BytesIO(binary_image)).convert("RGB")
  116. batch = split_image_into_tiles(np.array(image))
  117. import time
  118. start = time.process_time()
  119. with torch.no_grad():
  120. output = model(batch)
  121. elapsed = time.process_time() - start
  122. output_predictions = output.argmax(1)
  123. image = Image.fromarray(np.uint8(output_predictions.squeeze() * 255), "L")
  124. dead_tree_fraction = (
  125. torch.count_nonzero(output_predictions) / torch.numel(output_predictions)
  126. ).item()
  127. return {
  128. "image": image,
  129. "stats": {
  130. "fraction": str(dead_tree_fraction),
  131. "model_name": model_name,
  132. "elapsed": str(elapsed),
  133. },
  134. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...