├── .gitignore ├── 5_automatic_differentiation_implementation.ipynb ├── LICENSE ├── README.md └── python └── needle ├── __init__.py ├── autograd.py ├── backend_numpy.py ├── init ├── __init__.py └── init_basic.py └── ops ├── __init__.py └── ops_mathematic.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | data/ 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | *~ 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | pip-wheel-metadata/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lecture5 2 | 3 | This repo contains the infrastructure code needed for lecture5. 4 | It can be safely replaced by hw1 repo eventually. 5 | -------------------------------------------------------------------------------- /python/needle/__init__.py: -------------------------------------------------------------------------------- 1 | from . import ops 2 | from .ops import * 3 | from .autograd import Tensor, cpu, all_devices 4 | 5 | from .init import ones, zeros, zeros_like, ones_like 6 | 7 | from . import init 8 | 9 | -------------------------------------------------------------------------------- /python/needle/autograd.py: -------------------------------------------------------------------------------- 1 | """Core data structures.""" 2 | import needle 3 | from .backend_numpy import Device, cpu, all_devices 4 | from typing import List, Optional, NamedTuple, Tuple, Union 5 | from collections import namedtuple 6 | import numpy 7 | 8 | from needle import init 9 | 10 | # needle version 11 | LAZY_MODE = False 12 | TENSOR_COUNTER = 0 13 | 14 | # NOTE: we will import numpy as the array_api 15 | # as the backend for our computations, this line will change in later homeworks 16 | import numpy as array_api 17 | 18 | NDArray = numpy.ndarray 19 | 20 | 21 | class Op: 22 | """Operator definition.""" 23 | 24 | def __call__(self, *args): 25 | raise NotImplementedError() 26 | 27 | def compute(self, *args: Tuple[NDArray]): 28 | """Calculate forward pass of operator. 29 | 30 | Parameters 31 | ---------- 32 | input: np.ndarray 33 | A list of input arrays to the function 34 | 35 | Returns 36 | ------- 37 | output: nd.array 38 | Array output of the operation 39 | 40 | """ 41 | raise NotImplementedError() 42 | 43 | def gradient( 44 | self, out_grad: "Value", node: "Value" 45 | ) -> Union["Value", Tuple["Value"]]: 46 | """Compute partial adjoint for each input value for a given output adjoint. 47 | 48 | Parameters 49 | ---------- 50 | out_grad: Value 51 | The adjoint wrt to the output value. 52 | 53 | node: Value 54 | The value node of forward evaluation. 55 | 56 | Returns 57 | ------- 58 | input_grads: Value or Tuple[Value] 59 | A list containing partial gradient adjoints to be propagated to 60 | each of the input node. 61 | """ 62 | raise NotImplementedError() 63 | 64 | def gradient_as_tuple(self, out_grad: "Value", node: "Value") -> Tuple["Value"]: 65 | """Convenience method to always return a tuple from gradient call""" 66 | output = self.gradient(out_grad, node) 67 | if isinstance(output, tuple): 68 | return output 69 | elif isinstance(output, list): 70 | return tuple(output) 71 | else: 72 | return (output,) 73 | 74 | 75 | class TensorOp(Op): 76 | """Op class specialized to output tensors, will be alternate subclasses for other structures""" 77 | 78 | def __call__(self, *args): 79 | return Tensor.make_from_op(self, args) 80 | 81 | 82 | class TensorTupleOp(Op): 83 | """Op class specialized to output TensorTuple""" 84 | 85 | def __call__(self, *args): 86 | return TensorTuple.make_from_op(self, args) 87 | 88 | 89 | class Value: 90 | """A value in the computational graph.""" 91 | 92 | # trace of computational graph 93 | op: Optional[Op] 94 | inputs: List["Value"] 95 | # The following fields are cached fields for 96 | # dynamic computation 97 | cached_data: NDArray 98 | requires_grad: bool 99 | 100 | def realize_cached_data(self): 101 | """Run compute to realize the cached data""" 102 | # avoid recomputation 103 | if self.cached_data is not None: 104 | return self.cached_data 105 | # note: data implicitly calls realized cached data 106 | self.cached_data = self.op.compute( 107 | *[x.realize_cached_data() for x in self.inputs] 108 | ) 109 | return self.cached_data 110 | 111 | def is_leaf(self): 112 | return self.op is None 113 | 114 | def __del__(self): 115 | global TENSOR_COUNTER 116 | TENSOR_COUNTER -= 1 117 | 118 | def _init( 119 | self, 120 | op: Optional[Op], 121 | inputs: List["Tensor"], 122 | *, 123 | num_outputs: int = 1, 124 | cached_data: List[object] = None, 125 | requires_grad: Optional[bool] = None 126 | ): 127 | global TENSOR_COUNTER 128 | TENSOR_COUNTER += 1 129 | if requires_grad is None: 130 | requires_grad = any(x.requires_grad for x in inputs) 131 | self.op = op 132 | self.inputs = inputs 133 | self.num_outputs = num_outputs 134 | self.cached_data = cached_data 135 | self.requires_grad = requires_grad 136 | 137 | @classmethod 138 | def make_const(cls, data, *, requires_grad=False): 139 | value = cls.__new__(cls) 140 | value._init( 141 | None, 142 | [], 143 | cached_data=data, 144 | requires_grad=requires_grad, 145 | ) 146 | return value 147 | 148 | @classmethod 149 | def make_from_op(cls, op: Op, inputs: List["Value"]): 150 | value = cls.__new__(cls) 151 | value._init(op, inputs) 152 | 153 | if not LAZY_MODE: 154 | if not value.requires_grad: 155 | return value.detach() 156 | value.realize_cached_data() 157 | return value 158 | 159 | 160 | ### Not needed in HW1 161 | class TensorTuple(Value): 162 | """Represent a tuple of tensors. 163 | 164 | To keep things simple, we do not support nested tuples. 165 | """ 166 | 167 | def __len__(self): 168 | cdata = self.realize_cached_data() 169 | return len(cdata) 170 | 171 | def __getitem__(self, index: int): 172 | return needle.ops.tuple_get_item(self, index) 173 | 174 | def tuple(self): 175 | return tuple([x for x in self]) 176 | 177 | def __repr__(self): 178 | return "needle.TensorTuple" + str(self.tuple()) 179 | 180 | def __str__(self): 181 | return self.__repr__() 182 | 183 | def __add__(self, other): 184 | assert isinstance(other, TensorTuple) 185 | assert len(self) == len(other) 186 | return needle.ops.make_tuple(*[self[i] + other[i] for i in range(len(self))]) 187 | 188 | def detach(self): 189 | """Create a new tensor that shares the data but detaches from the graph.""" 190 | return Tuple.make_const(self.realize_cached_data()) 191 | 192 | 193 | class Tensor(Value): 194 | grad: "Tensor" 195 | 196 | def __init__( 197 | self, 198 | array, 199 | *, 200 | device: Optional[Device] = None, 201 | dtype=None, 202 | requires_grad=True, 203 | **kwargs 204 | ): 205 | if isinstance(array, Tensor): 206 | if device is None: 207 | device = array.device 208 | if dtype is None: 209 | dtype = array.dtype 210 | if device == array.device and dtype == array.dtype: 211 | cached_data = array.realize_cached_data() 212 | else: 213 | # fall back, copy through numpy conversion 214 | cached_data = Tensor._array_from_numpy( 215 | array.numpy(), device=device, dtype=dtype 216 | ) 217 | else: 218 | device = device if device else cpu() 219 | cached_data = Tensor._array_from_numpy(array, device=device, dtype=dtype) 220 | 221 | self._init( 222 | None, 223 | [], 224 | cached_data=cached_data, 225 | requires_grad=requires_grad, 226 | ) 227 | 228 | @staticmethod 229 | def _array_from_numpy(numpy_array, device, dtype): 230 | if array_api is numpy: 231 | return numpy.array(numpy_array, dtype=dtype) 232 | return array_api.array(numpy_array, device=device, dtype=dtype) 233 | 234 | @staticmethod 235 | def make_from_op(op: Op, inputs: List["Value"]): 236 | tensor = Tensor.__new__(Tensor) 237 | tensor._init(op, inputs) 238 | if not LAZY_MODE: 239 | if not tensor.requires_grad: 240 | return tensor.detach() 241 | tensor.realize_cached_data() 242 | return tensor 243 | 244 | @staticmethod 245 | def make_const(data, requires_grad=False): 246 | tensor = Tensor.__new__(Tensor) 247 | tensor._init( 248 | None, 249 | [], 250 | cached_data=data 251 | if not isinstance(data, Tensor) 252 | else data.realize_cached_data(), 253 | requires_grad=requires_grad, 254 | ) 255 | return tensor 256 | 257 | @property 258 | def data(self): 259 | return self.detach() 260 | 261 | @data.setter 262 | def data(self, value): 263 | assert isinstance(value, Tensor) 264 | assert value.dtype == self.dtype, "%s %s" % ( 265 | value.dtype, 266 | self.dtype, 267 | ) 268 | self.cached_data = value.realize_cached_data() 269 | 270 | def detach(self): 271 | """Create a new tensor that shares the data but detaches from the graph.""" 272 | return Tensor.make_const(self.realize_cached_data()) 273 | 274 | @property 275 | def shape(self): 276 | return self.realize_cached_data().shape 277 | 278 | @property 279 | def dtype(self): 280 | return self.realize_cached_data().dtype 281 | 282 | @property 283 | def device(self): 284 | data = self.realize_cached_data() 285 | # numpy array always sits on cpu 286 | if array_api is numpy: 287 | return cpu() 288 | return data.device 289 | 290 | def backward(self, out_grad=None): 291 | out_grad = ( 292 | out_grad 293 | if out_grad 294 | else init.ones(*self.shape, dtype=self.dtype, device=self.device) 295 | ) 296 | compute_gradient_of_variables(self, out_grad) 297 | 298 | def __repr__(self): 299 | return "needle.Tensor(" + str(self.realize_cached_data()) + ")" 300 | 301 | def __str__(self): 302 | return self.realize_cached_data().__str__() 303 | 304 | def numpy(self): 305 | data = self.realize_cached_data() 306 | if array_api is numpy: 307 | return data 308 | return data.numpy() 309 | 310 | def __add__(self, other): 311 | if isinstance(other, Tensor): 312 | return needle.ops.EWiseAdd()(self, other) 313 | else: 314 | return needle.ops.AddScalar(other)(self) 315 | 316 | def __mul__(self, other): 317 | if isinstance(other, Tensor): 318 | return needle.ops.EWiseMul()(self, other) 319 | else: 320 | return needle.ops.MulScalar(other)(self) 321 | 322 | def __pow__(self, other): 323 | if isinstance(other, Tensor): 324 | return needle.ops.EWisePow()(self, other) 325 | else: 326 | return needle.ops.PowerScalar(other)(self) 327 | 328 | def __sub__(self, other): 329 | if isinstance(other, Tensor): 330 | return needle.ops.EWiseAdd()(self, needle.ops.Negate()(other)) 331 | else: 332 | return needle.ops.AddScalar(-other)(self) 333 | 334 | def __truediv__(self, other): 335 | if isinstance(other, Tensor): 336 | return needle.ops.EWiseDiv()(self, other) 337 | else: 338 | return needle.ops.DivScalar(other)(self) 339 | 340 | def __matmul__(self, other): 341 | return needle.ops.MatMul()(self, other) 342 | 343 | def matmul(self, other): 344 | return needle.ops.MatMul()(self, other) 345 | 346 | def sum(self, axes=None): 347 | return needle.ops.Summation(axes)(self) 348 | 349 | def broadcast_to(self, shape): 350 | return needle.ops.BroadcastTo(shape)(self) 351 | 352 | def reshape(self, shape): 353 | return needle.ops.Reshape(shape)(self) 354 | 355 | def __neg__(self): 356 | return needle.ops.Negate()(self) 357 | 358 | def transpose(self, axes=None): 359 | return needle.ops.Transpose(axes)(self) 360 | 361 | __radd__ = __add__ 362 | __rmul__ = __mul__ 363 | __rsub__ = __sub__ 364 | __rmatmul__ = __matmul__ 365 | 366 | 367 | def compute_gradient_of_variables(output_tensor, out_grad): 368 | """Take gradient of output node with respect to each node in node_list. 369 | 370 | Store the computed result in the grad field of each Variable. 371 | """ 372 | # a map from node to a list of gradient contributions from each output node 373 | node_to_output_grads_list: Dict[Tensor, List[Tensor]] = {} 374 | # Special note on initializing gradient of 375 | # We are really taking a derivative of the scalar reduce_sum(output_node) 376 | # instead of the vector output_node. But this is the common case for loss function. 377 | node_to_output_grads_list[output_tensor] = [out_grad] 378 | 379 | # Traverse graph in reverse topological order given the output_node that we are taking gradient wrt. 380 | reverse_topo_order = list(reversed(find_topo_sort([output_tensor]))) 381 | 382 | ### BEGIN YOUR SOLUTION 383 | raise NotImplementedError() 384 | ### END YOUR SOLUTION 385 | 386 | 387 | def find_topo_sort(node_list: List[Value]) -> List[Value]: 388 | """Given a list of nodes, return a topological sort list of nodes ending in them. 389 | 390 | A simple algorithm is to do a post-order DFS traversal on the given nodes, 391 | going backwards based on input edges. Since a node is added to the ordering 392 | after all its predecessors are traversed due to post-order DFS, we get a topological 393 | sort. 394 | """ 395 | ### BEGIN YOUR SOLUTION 396 | raise NotImplementedError() 397 | ### END YOUR SOLUTION 398 | 399 | 400 | def topo_sort_dfs(node, visited, topo_order): 401 | """Post-order DFS""" 402 | ### BEGIN YOUR SOLUTION 403 | raise NotImplementedError() 404 | ### END YOUR SOLUTION 405 | 406 | 407 | ############################## 408 | ####### Helper Methods ####### 409 | ############################## 410 | 411 | 412 | def sum_node_list(node_list): 413 | """Custom sum function in order to avoid create redundant nodes in Python sum implementation.""" 414 | from operator import add 415 | from functools import reduce 416 | 417 | return reduce(add, node_list) 418 | -------------------------------------------------------------------------------- /python/needle/backend_numpy.py: -------------------------------------------------------------------------------- 1 | """This file defies specific implementations of devices when using numpy as NDArray backend. 2 | """ 3 | import numpy 4 | 5 | 6 | class Device: 7 | """Baseclass of all device""" 8 | 9 | 10 | class CPUDevice(Device): 11 | """Represents data that sits in CPU""" 12 | 13 | def __repr__(self): 14 | return "needle.cpu()" 15 | 16 | def __hash__(self): 17 | return self.__repr__().__hash__() 18 | 19 | def __eq__(self, other): 20 | return isinstance(other, CPUDevice) 21 | 22 | def enabled(self): 23 | return True 24 | 25 | def zeros(self, *shape, dtype="float32"): 26 | return numpy.zeros(shape, dtype=dtype) 27 | 28 | def ones(self, *shape, dtype="float32"): 29 | return numpy.ones(shape, dtype=dtype) 30 | 31 | def randn(self, *shape): 32 | # note: numpy doesn't support types within standard random routines, and 33 | # .astype("float32") does work if we're generating a singleton 34 | return numpy.random.randn(*shape) 35 | 36 | def rand(self, *shape): 37 | # note: numpy doesn't support types within standard random routines, and 38 | # .astype("float32") does work if we're generating a singleton 39 | return numpy.random.rand(*shape) 40 | 41 | def one_hot(self, n, i, dtype="float32"): 42 | return numpy.eye(n, dtype=dtype)[i] 43 | 44 | def empty(self, shape, dtype="float32"): 45 | return numpy.empty(shape, dtype=dtype) 46 | 47 | def full(self, shape, fill_value, dtype="float32"): 48 | return numpy.full(shape, fill_value, dtype=dtype) 49 | 50 | 51 | def cpu(): 52 | """Return cpu device""" 53 | return CPUDevice() 54 | 55 | 56 | def default_device(): 57 | return cpu() 58 | 59 | 60 | def all_devices(): 61 | """return a list of all available devices""" 62 | return [cpu()] 63 | -------------------------------------------------------------------------------- /python/needle/init/__init__.py: -------------------------------------------------------------------------------- 1 | from .init_basic import * 2 | 3 | -------------------------------------------------------------------------------- /python/needle/init/init_basic.py: -------------------------------------------------------------------------------- 1 | import math 2 | import needle as ndl 3 | 4 | 5 | def rand(*shape, low=0.0, high=1.0, device=None, dtype="float32", requires_grad=False): 6 | """Generate random numbers uniform between low and high""" 7 | device = ndl.cpu() if device is None else device 8 | array = device.rand(*shape) * (high - low) + low 9 | return ndl.Tensor(array, device=device, dtype=dtype, requires_grad=requires_grad) 10 | 11 | 12 | def randn(*shape, mean=0.0, std=1.0, device=None, dtype="float32", requires_grad=False): 13 | """Generate random normal with specified mean and std deviation""" 14 | device = ndl.cpu() if device is None else device 15 | array = device.randn(*shape) * std + mean 16 | return ndl.Tensor(array, device=device, dtype=dtype, requires_grad=requires_grad) 17 | 18 | 19 | def constant(*shape, c=1.0, device=None, dtype="float32", requires_grad=False): 20 | """Generate constant Tensor""" 21 | device = ndl.cpu() if device is None else device 22 | array = device.ones(*shape, dtype=dtype) * c # note: can change dtype 23 | return ndl.Tensor(array, device=device, dtype=dtype, requires_grad=requires_grad) 24 | 25 | 26 | def ones(*shape, device=None, dtype="float32", requires_grad=False): 27 | """Generate all-ones Tensor""" 28 | return constant( 29 | *shape, c=1.0, device=device, dtype=dtype, requires_grad=requires_grad 30 | ) 31 | 32 | 33 | def zeros(*shape, device=None, dtype="float32", requires_grad=False): 34 | """Generate all-zeros Tensor""" 35 | return constant( 36 | *shape, c=0.0, device=device, dtype=dtype, requires_grad=requires_grad 37 | ) 38 | 39 | 40 | def randb(*shape, p=0.5, device=None, dtype="bool", requires_grad=False): 41 | """Generate binary random Tensor""" 42 | device = ndl.cpu() if device is None else device 43 | array = device.rand(*shape) <= p 44 | return ndl.Tensor(array, device=device, dtype=dtype, requires_grad=requires_grad) 45 | 46 | 47 | def one_hot(n, i, device=None, dtype="float32", requires_grad=False): 48 | """Generate one-hot encoding Tensor""" 49 | device = ndl.cpu() if device is None else device 50 | return ndl.Tensor( 51 | device.one_hot(n, i.numpy(), dtype=dtype), 52 | device=device, 53 | requires_grad=requires_grad, 54 | ) 55 | 56 | 57 | def zeros_like(array, *, device=None, requires_grad=False): 58 | device = device if device else array.device 59 | return zeros( 60 | *array.shape, dtype=array.dtype, device=device, requires_grad=requires_grad 61 | ) 62 | 63 | 64 | def ones_like(array, *, device=None, requires_grad=False): 65 | device = device if device else array.device 66 | return ones( 67 | *array.shape, dtype=array.dtype, device=device, requires_grad=requires_grad 68 | ) 69 | -------------------------------------------------------------------------------- /python/needle/ops/__init__.py: -------------------------------------------------------------------------------- 1 | from .ops_mathematic import * 2 | 3 | -------------------------------------------------------------------------------- /python/needle/ops/ops_mathematic.py: -------------------------------------------------------------------------------- 1 | """Operator implementations.""" 2 | 3 | from numbers import Number 4 | from typing import Optional, List, Tuple, Union 5 | 6 | from ..autograd import NDArray 7 | from ..autograd import Op, Tensor, Value, TensorOp 8 | from ..autograd import TensorTuple, TensorTupleOp 9 | import numpy 10 | 11 | # NOTE: we will import numpy as the array_api 12 | # as the backend for our computations, this line will change in later homeworks 13 | 14 | import numpy as array_api 15 | 16 | 17 | class EWiseAdd(TensorOp): 18 | def compute(self, a: NDArray, b: NDArray): 19 | return a + b 20 | 21 | def gradient(self, out_grad: Tensor, node: Tensor): 22 | return out_grad, out_grad 23 | 24 | 25 | def add(a, b): 26 | return EWiseAdd()(a, b) 27 | 28 | 29 | class AddScalar(TensorOp): 30 | def __init__(self, scalar): 31 | self.scalar = scalar 32 | 33 | def compute(self, a: NDArray): 34 | return a + self.scalar 35 | 36 | def gradient(self, out_grad: Tensor, node: Tensor): 37 | return out_grad 38 | 39 | 40 | def add_scalar(a, scalar): 41 | return AddScalar(scalar)(a) 42 | 43 | 44 | class EWiseMul(TensorOp): 45 | def compute(self, a: NDArray, b: NDArray): 46 | return a * b 47 | 48 | def gradient(self, out_grad: Tensor, node: Tensor): 49 | lhs, rhs = node.inputs 50 | return out_grad * rhs, out_grad * lhs 51 | 52 | 53 | def multiply(a, b): 54 | return EWiseMul()(a, b) 55 | 56 | 57 | class MulScalar(TensorOp): 58 | def __init__(self, scalar): 59 | self.scalar = scalar 60 | 61 | def compute(self, a: NDArray): 62 | return a * self.scalar 63 | 64 | def gradient(self, out_grad: Tensor, node: Tensor): 65 | return (out_grad * self.scalar,) 66 | 67 | 68 | def mul_scalar(a, scalar): 69 | return MulScalar(scalar)(a) 70 | 71 | 72 | class PowerScalar(TensorOp): 73 | """Op raise a tensor to an (integer) power.""" 74 | 75 | def __init__(self, scalar: int): 76 | self.scalar = scalar 77 | 78 | def compute(self, a: NDArray) -> NDArray: 79 | ### BEGIN YOUR SOLUTION 80 | raise NotImplementedError() 81 | ### END YOUR SOLUTION 82 | 83 | def gradient(self, out_grad, node): 84 | ### BEGIN YOUR SOLUTION 85 | raise NotImplementedError() 86 | ### END YOUR SOLUTION 87 | 88 | 89 | def power_scalar(a, scalar): 90 | return PowerScalar(scalar)(a) 91 | 92 | 93 | class EWisePow(TensorOp): 94 | """Op to element-wise raise a tensor to a power.""" 95 | 96 | def compute(self, a: NDArray, b: NDArray) -> NDArray: 97 | return a**b 98 | 99 | def gradient(self, out_grad, node): 100 | if not isinstance(node.inputs[0], NDArray) or not isinstance( 101 | node.inputs[1], NDArray 102 | ): 103 | raise ValueError("Both inputs must be tensors (NDArray).") 104 | 105 | a, b = node.inputs[0], node.inputs[1] 106 | grad_a = out_grad * b * (a ** (b - 1)) 107 | grad_b = out_grad * (a**b) * array_api.log(a.data) 108 | return grad_a, grad_b 109 | 110 | def power(a, b): 111 | return EWisePow()(a, b) 112 | 113 | 114 | class EWiseDiv(TensorOp): 115 | """Op to element-wise divide two nodes.""" 116 | 117 | def compute(self, a, b): 118 | ### BEGIN YOUR SOLUTION 119 | raise NotImplementedError() 120 | ### END YOUR SOLUTION 121 | 122 | def gradient(self, out_grad, node): 123 | ### BEGIN YOUR SOLUTION 124 | raise NotImplementedError() 125 | ### END YOUR SOLUTION 126 | 127 | 128 | def divide(a, b): 129 | return EWiseDiv()(a, b) 130 | 131 | 132 | class DivScalar(TensorOp): 133 | def __init__(self, scalar): 134 | self.scalar = scalar 135 | 136 | def compute(self, a): 137 | ### BEGIN YOUR SOLUTION 138 | raise NotImplementedError() 139 | ### END YOUR SOLUTION 140 | 141 | def gradient(self, out_grad, node): 142 | ### BEGIN YOUR SOLUTION 143 | raise NotImplementedError() 144 | ### END YOUR SOLUTION 145 | 146 | 147 | def divide_scalar(a, scalar): 148 | return DivScalar(scalar)(a) 149 | 150 | 151 | class Transpose(TensorOp): 152 | def __init__(self, axes: Optional[tuple] = None): 153 | self.axes = axes 154 | 155 | def compute(self, a): 156 | ### BEGIN YOUR SOLUTION 157 | raise NotImplementedError() 158 | ### END YOUR SOLUTION 159 | 160 | def gradient(self, out_grad, node): 161 | ### BEGIN YOUR SOLUTION 162 | raise NotImplementedError() 163 | ### END YOUR SOLUTION 164 | 165 | 166 | def transpose(a, axes=None): 167 | return Transpose(axes)(a) 168 | 169 | 170 | class Reshape(TensorOp): 171 | def __init__(self, shape): 172 | self.shape = shape 173 | 174 | def compute(self, a): 175 | ### BEGIN YOUR SOLUTION 176 | raise NotImplementedError() 177 | ### END YOUR SOLUTION 178 | 179 | def gradient(self, out_grad, node): 180 | ### BEGIN YOUR SOLUTION 181 | raise NotImplementedError() 182 | ### END YOUR SOLUTION 183 | 184 | 185 | def reshape(a, shape): 186 | return Reshape(shape)(a) 187 | 188 | 189 | class BroadcastTo(TensorOp): 190 | def __init__(self, shape): 191 | self.shape = shape 192 | 193 | def compute(self, a): 194 | ### BEGIN YOUR SOLUTION 195 | raise NotImplementedError() 196 | ### END YOUR SOLUTION 197 | 198 | def gradient(self, out_grad, node): 199 | ### BEGIN YOUR SOLUTION 200 | raise NotImplementedError() 201 | ### END YOUR SOLUTION 202 | 203 | 204 | def broadcast_to(a, shape): 205 | return BroadcastTo(shape)(a) 206 | 207 | 208 | class Summation(TensorOp): 209 | def __init__(self, axes: Optional[tuple] = None): 210 | self.axes = axes 211 | 212 | def compute(self, a): 213 | ### BEGIN YOUR SOLUTION 214 | raise NotImplementedError() 215 | ### END YOUR SOLUTION 216 | 217 | def gradient(self, out_grad, node): 218 | ### BEGIN YOUR SOLUTION 219 | raise NotImplementedError() 220 | ### END YOUR SOLUTION 221 | 222 | 223 | def summation(a, axes=None): 224 | return Summation(axes)(a) 225 | 226 | 227 | class MatMul(TensorOp): 228 | def compute(self, a, b): 229 | ### BEGIN YOUR SOLUTION 230 | raise NotImplementedError() 231 | ### END YOUR SOLUTION 232 | 233 | def gradient(self, out_grad, node): 234 | ### BEGIN YOUR SOLUTION 235 | raise NotImplementedError() 236 | ### END YOUR SOLUTION 237 | 238 | 239 | def matmul(a, b): 240 | return MatMul()(a, b) 241 | 242 | 243 | class Negate(TensorOp): 244 | def compute(self, a): 245 | ### BEGIN YOUR SOLUTION 246 | raise NotImplementedError() 247 | ### END YOUR SOLUTION 248 | 249 | def gradient(self, out_grad, node): 250 | ### BEGIN YOUR SOLUTION 251 | raise NotImplementedError() 252 | ### END YOUR SOLUTION 253 | 254 | 255 | def negate(a): 256 | return Negate()(a) 257 | 258 | 259 | class Log(TensorOp): 260 | def compute(self, a): 261 | ### BEGIN YOUR SOLUTION 262 | raise NotImplementedError() 263 | ### END YOUR SOLUTION 264 | 265 | def gradient(self, out_grad, node): 266 | ### BEGIN YOUR SOLUTION 267 | raise NotImplementedError() 268 | ### END YOUR SOLUTION 269 | 270 | 271 | def log(a): 272 | return Log()(a) 273 | 274 | 275 | class Exp(TensorOp): 276 | def compute(self, a): 277 | ### BEGIN YOUR SOLUTION 278 | raise NotImplementedError() 279 | ### END YOUR SOLUTION 280 | 281 | def gradient(self, out_grad, node): 282 | ### BEGIN YOUR SOLUTION 283 | raise NotImplementedError() 284 | ### END YOUR SOLUTION 285 | 286 | 287 | def exp(a): 288 | return Exp()(a) 289 | 290 | 291 | class ReLU(TensorOp): 292 | def compute(self, a): 293 | ### BEGIN YOUR SOLUTION 294 | raise NotImplementedError() 295 | ### END YOUR SOLUTION 296 | 297 | def gradient(self, out_grad, node): 298 | ### BEGIN YOUR SOLUTION 299 | raise NotImplementedError() 300 | ### END YOUR SOLUTION 301 | 302 | 303 | def relu(a): 304 | return ReLU()(a) 305 | --------------------------------------------------------------------------------