If you have found these useful in your research, presentations, school work, projects or workshops, feel free to cite using this DOI. conv2.weight=nn.Parameter(torch.from_numpy(b).float().unsqueeze(0).unsqueeze(0)) Short story taking place on a toroidal planet or moon involving flying. tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], # A scalar value for spacing modifies the relationship between tensor indices, # and input coordinates by multiplying the indices to find the, # coordinates. from PIL import Image To approximate the derivatives, it convolve the image with a kernel and the most common convolving filter here we using is sobel operator, which is a small, separable and integer valued filter that outputs a gradient vector or a norm. \[\frac{\partial Q}{\partial a} = 9a^2 The accuracy of the model is calculated on the test data and shows the percentage of the right prediction. Does ZnSO4 + H2 at high pressure reverses to Zn + H2SO4? You can check which classes our model can predict the best. 2.pip install tensorboardX . This is detailed in the Keyword Arguments section below. It is simple mnist model. external_grad represents \(\vec{v}\). The same exclusionary functionality is available as a context manager in import numpy as np torch.no_grad(), In-place operations & Multithreaded Autograd, Example implementation of reverse-mode autodiff, Total running time of the script: ( 0 minutes 0.886 seconds), Download Python source code: autograd_tutorial.py, Download Jupyter notebook: autograd_tutorial.ipynb, Access comprehensive developer documentation for PyTorch, Get in-depth tutorials for beginners and advanced developers, Find development resources and get your questions answered. J. Rafid Siddiqui, PhD. (A clear and concise description of what the bug is), What OS? img = Image.open(/home/soumya/Downloads/PhotographicImageSynthesis_master/result_256p/final/frankfurt_000000_000294_gtFine_color.png.jpg).convert(LA) All images are pre-processed with mean and std of the ImageNet dataset before being fed to the model. Numerical gradients . They are considered as Weak. 3 Likes It is very similar to creating a tensor, all you need to do is to add an additional argument. The number of out-channels in the layer serves as the number of in-channels to the next layer. print(w1.grad) Once the training is complete, you should expect to see the output similar to the below. How to check the output gradient by each layer in pytorch in my code? The gradient of ggg is estimated using samples. Please find the following lines in the console and paste them below. How to follow the signal when reading the schematic? If you mean gradient of each perceptron of each layer then, What you mention is parameter gradient I think(taking. This is why you got 0.333 in the grad. Powered by Discourse, best viewed with JavaScript enabled, http://pytorch.org/docs/0.3.0/torch.html?highlight=torch%20mean#torch.mean. operations (along with the resulting new tensors) in a directed acyclic Neural networks (NNs) are a collection of nested functions that are Pytho. YES To extract the feature representations more precisely we can compute the image gradient to the edge constructions of a given image. Interested in learning more about neural network with PyTorch? Mutually exclusive execution using std::atomic? gradient of \(l\) with respect to \(\vec{x}\): This characteristic of vector-Jacobian product is what we use in the above example; To learn more, see our tips on writing great answers. These functions are defined by parameters The output tensor of an operation will require gradients even if only a In PyTorch, the neural network package contains various loss functions that form the building blocks of deep neural networks. tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], # The following example is a replication of the previous one with explicit, second-order accurate central differences method. \end{array}\right)\], \[\vec{v} In our case it will tell us how many images from the 10,000-image test set our model was able to classify correctly after each training iteration. I have some problem with getting the output gradient of input. shape (1,1000). Note that when dim is specified the elements of Building an Image Classification Model From Scratch Using PyTorch | by Benedict Neo | bitgrit Data Science Publication | Medium 500 Apologies, but something went wrong on our end. # 0, 1 translate to coordinates of [0, 2]. Short story taking place on a toroidal planet or moon involving flying. So coming back to looking at weights and biases, you can access them per layer. Tensors with Gradients Creating Tensors with Gradients Allows accumulation of gradients Method 1: Create tensor with gradients Finally, we trained and tested our model on the CIFAR100 dataset, and the model seemed to perform well on the test dataset with 75% accuracy. Lets assume a and b to be parameters of an NN, and Q What exactly is requires_grad? please see www.lfprojects.org/policies/. Learn more, including about available controls: Cookies Policy. the partial gradient in every dimension is computed. We will use a framework called PyTorch to implement this method. torch.autograd is PyTorch's automatic differentiation engine that powers neural network training. Awesome, thanks a lot, and what if I would love to know the "output" gradient for each layer? I have one of the simplest differentiable solutions. So model[0].weight and model[0].bias are the weights and biases of the first layer. You will set it as 0.001. Not the answer you're looking for? from torchvision import transforms Why, yes! , My bad, I didn't notice it, sorry for the misunderstanding, I have further edited the answer, How to get the output gradient w.r.t input, discuss.pytorch.org/t/gradients-of-output-w-r-t-input/26905/2, How Intuit democratizes AI development across teams through reusability. The only parameters that compute gradients are the weights and bias of model.fc. and its corresponding label initialized to some random values. If \(\vec{v}\) happens to be the gradient of a scalar function \(l=g\left(\vec{y}\right)\): then by the chain rule, the vector-Jacobian product would be the Recovering from a blunder I made while emailing a professor. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie We've added a "Necessary cookies only" option to the cookie consent popup. \vdots\\ In a forward pass, autograd does two things simultaneously: run the requested operation to compute a resulting tensor, and. To learn more, see our tips on writing great answers. They're most commonly used in computer vision applications. i understand that I have native, What GPU are you using? At each image point, the gradient of image intensity function results a 2D vector which have the components of derivatives in the vertical as well as in the horizontal directions. - Satya Prakash Dash May 30, 2021 at 3:36 What you mention is parameter gradient I think (taking y = wx + b parameter gradient is w and b here)? To get the vertical and horizontal edge representation, combines the resulting gradient approximations, by taking the root of squared sum of these approximations, Gx and Gy. maybe this question is a little stupid, any help appreciated! X.save(fake_grad.png), Thanks ! RuntimeError If img is not a 4D tensor. privacy statement. Is it possible to show the code snippet? Have a question about this project? By default, when spacing is not db_config.json file from /models/dreambooth/MODELNAME/db_config.json In your answer the gradients are swapped. In resnet, the classifier is the last linear layer model.fc. For a more detailed walkthrough The PyTorch Foundation is a project of The Linux Foundation. For example, for the operation mean, we have: How can I flush the output of the print function? Connect and share knowledge within a single location that is structured and easy to search. We'll run only two iterations [train(2)] over the training set, so the training process won't take too long. why the grad is changed, what the backward function do? If you enjoyed this article, please recommend it and share it! \frac{\partial y_{1}}{\partial x_{1}} & \cdots & \frac{\partial y_{1}}{\partial x_{n}}\\ Next, we load an optimizer, in this case SGD with a learning rate of 0.01 and momentum of 0.9. Before we get into the saliency map, let's talk about the image classification. The convolution layer is a main layer of CNN which helps us to detect features in images. The PyTorch Foundation supports the PyTorch open source Can archive.org's Wayback Machine ignore some query terms? the tensor that all allows gradients accumulation, Create tensor of size 2x1 filled with 1's that requires gradient, Simple linear equation with x tensor created, We should get a value of 20 by replicating this simple equation, Backward should be called only on a scalar (i.e. [0, 0, 0], Letting xxx be an interior point and x+hrx+h_rx+hr be point neighboring it, the partial gradient at torch.autograd is PyTorchs automatic differentiation engine that powers This package contains modules, extensible classes and all the required components to build neural networks. To analyze traffic and optimize your experience, we serve cookies on this site. For tensors that dont require Maybe implemented with Convolution 2d filter with require_grad=false (where you set the weights to sobel filters). What video game is Charlie playing in Poker Face S01E07? P=transforms.Compose([transforms.ToPILImage()]), ten=torch.unbind(T(img)) If a law is new but its interpretation is vague, can the courts directly ask the drafters the intent and official interpretation of their law? Lets take a look at how autograd collects gradients. w1 = Variable(torch.Tensor([1.0,2.0,3.0]),requires_grad=True) automatically compute the gradients using the chain rule. So,dy/dx_i = 1/N, where N is the element number of x. Then, we used PyTorch to build our VGG-16 model from scratch along with understanding different types of layers available in torch. project, which has been established as PyTorch Project a Series of LF Projects, LLC. Learn how our community solves real, everyday machine learning problems with PyTorch. To analyze traffic and optimize your experience, we serve cookies on this site. Autograd then calculates and stores the gradients for each model parameter in the parameters .grad attribute. How to properly zero your gradient, perform backpropagation, and update your model parameters most deep learning practitioners new to PyTorch make a mistake in this step ; As the current maintainers of this site, Facebooks Cookies Policy applies. From wiki: If the gradient of a function is non-zero at a point p, the direction of the gradient is the direction in which the function increases most quickly from p, and the magnitude of the gradient is the rate of increase in that direction.. Model accuracy is different from the loss value. How should I do it? the parameters using gradient descent. single input tensor has requires_grad=True. As before, we load a pretrained resnet18 model, and freeze all the parameters. We need to explicitly pass a gradient argument in Q.backward() because it is a vector. Next, we run the input data through the model through each of its layers to make a prediction. Finally, lets add the main code. y = mean(x) = 1/N * \sum x_i If you've done the previous step of this tutorial, you've handled this already. \vdots\\ Reply 'OK' Below to acknowledge that you did this. Have you updated Dreambooth to the latest revision? The first is: import torch import torch.nn.functional as F def gradient_1order (x,h_x=None,w_x=None): Can we get the gradients of each epoch? [-1, -2, -1]]), b = b.view((1,1,3,3)) how to compute the gradient of an image in pytorch. rev2023.3.3.43278. Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2. If you need to compute the gradient with respect to the input you can do so by calling sample_img.requires_grad_(), or by setting sample_img.requires_grad = True, as suggested in your comments. Computes Gradient Computation of Image of a given image using finite difference. Notice although we register all the parameters in the optimizer, X=P(G) to an output is the same as the tensors mapping of indices to values. Additionally, if you don't need the gradients of the model, you can set their gradient requirements off: Thanks for contributing an answer to Stack Overflow! The below sections detail the workings of autograd - feel free to skip them. Equivalently, we can also aggregate Q into a scalar and call backward implicitly, like Q.sum().backward(). Feel free to try divisions, mean or standard deviation! from torch.autograd import Variable (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000]. Lets walk through a small example to demonstrate this. Revision 825d17f3. import torch In finetuning, we freeze most of the model and typically only modify the classifier layers to make predictions on new labels. Or do I have the reason for my issue completely wrong to begin with? Thanks for your time. A CNN is a class of neural networks, defined as multilayered neural networks designed to detect complex features in data. YES Kindly read the entire form below and fill it out with the requested information. accurate if ggg is in C3C^3C3 (it has at least 3 continuous derivatives), and the estimation can be Next, we loaded and pre-processed the CIFAR100 dataset using torchvision. As the current maintainers of this site, Facebooks Cookies Policy applies. img (Tensor) An (N, C, H, W) input tensor where C is the number of image channels, Tuple of (dy, dx) with each gradient of shape [N, C, H, W]. The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie We've added a "Necessary cookies only" option to the cookie consent popup. A tensor without gradients just for comparison. Smaller kernel sizes will reduce computational time and weight sharing. good_gradient = torch.ones(*image_shape) / torch.sqrt(image_size) In above the torch.ones(*image_shape) is just filling a 4-D Tensor filled up with 1 and then torch.sqrt(image_size) is just representing the value of tensor(28.) = conv1.weight=nn.Parameter(torch.from_numpy(a).float().unsqueeze(0).unsqueeze(0)), G_x=conv1(Variable(x)).data.view(1,256,512), b=np.array([[1, 2, 1],[0,0,0],[-1,-2,-1]]) the coordinates are (t0[1], t1[2], t2[3]), dim (int, list of int, optional) the dimension or dimensions to approximate the gradient over. This is because sobel_h finds horizontal edges, which are discovered by the derivative in the y direction. \end{array}\right)\left(\begin{array}{c} Forward Propagation: In forward prop, the NN makes its best guess (consisting of weights and biases), which in PyTorch are stored in this worked. The console window will pop up and will be able to see the process of training. So, what I am trying to understand why I need to divide the 4-D Tensor by tensor(28.) For this example, we load a pretrained resnet18 model from torchvision. This is a perfect answer that I want to know!! # doubling the spacing between samples halves the estimated partial gradients. What is the point of Thrower's Bandolier? What is the correct way to screw wall and ceiling drywalls? Already on GitHub? edge_order (int, optional) 1 or 2, for first-order or If you do not do either of the methods above, you'll realize you will get False for checking for gradients. a = torch.Tensor([[1, 0, -1], to get the good_gradient Welcome to our tutorial on debugging and Visualisation in PyTorch. Background Neural networks (NNs) are a collection of nested functions that are executed on some input data. Now, you can test the model with batch of images from our test set. Synthesis (ERGAS), Learned Perceptual Image Patch Similarity (LPIPS), Structural Similarity Index Measure (SSIM), Symmetric Mean Absolute Percentage Error (SMAPE). By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. My Name is Anumol, an engineering post graduate. Learn how our community solves real, everyday machine learning problems with PyTorch. # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate, # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension. This is a good result for a basic model trained for short period of time! [2, 0, -2], issue will be automatically closed. \end{array}\right)\], # check if collected gradients are correct, # Freeze all the parameters in the network, Deep Learning with PyTorch: A 60 Minute Blitz, Visualizing Models, Data, and Training with TensorBoard, TorchVision Object Detection Finetuning Tutorial, Transfer Learning for Computer Vision Tutorial, Optimizing Vision Transformer Model for Deployment, Language Modeling with nn.Transformer and TorchText, Fast Transformer Inference with Better Transformer, NLP From Scratch: Classifying Names with a Character-Level RNN, NLP From Scratch: Generating Names with a Character-Level RNN, NLP From Scratch: Translation with a Sequence to Sequence Network and Attention, Text classification with the torchtext library, Real Time Inference on Raspberry Pi 4 (30 fps! Browse other questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide. Low-Highthreshold: the pixels with an intensity higher than the threshold are set to 1 and the others to 0. Describe the bug. backwards from the output, collecting the derivatives of the error with Lets run the test! torch.gradient(input, *, spacing=1, dim=None, edge_order=1) List of Tensors Estimates the gradient of a function g : \mathbb {R}^n \rightarrow \mathbb {R} g: Rn R in one or more dimensions using the second-order accurate central differences method. gradient of Q w.r.t. \frac{\partial \bf{y}}{\partial x_{1}} & PyTorch Forums How to calculate the gradient of images? As you defined, the loss value will be printed every 1,000 batches of images or five times for every iteration over the training set. By querying the PyTorch Docs, torch.autograd.grad may be useful. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. requires_grad=True. The nodes represent the backward functions To analyze traffic and optimize your experience, we serve cookies on this site. python pytorch from torch.autograd import Variable Make sure the dropdown menus in the top toolbar are set to Debug. In this tutorial, you will use a Classification loss function based on Define the loss function with Classification Cross-Entropy loss and an Adam Optimizer. How do I print colored text to the terminal? root. By clicking Accept all cookies, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. gradient computation DAG. \], \[\frac{\partial Q}{\partial b} = -2b In this section, you will get a conceptual understanding of how autograd helps a neural network train. input (Tensor) the tensor that represents the values of the function, spacing (scalar, list of scalar, list of Tensor, optional) spacing can be used to modify By clicking Sign up for GitHub, you agree to our terms of service and G_y = F.conv2d(x, b), G = torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2)) Find resources and get questions answered, A place to discuss PyTorch code, issues, install, research, Discover, publish, and reuse pre-trained models. Mathematically, the value at each interior point of a partial derivative conv1=nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False) Manually and Automatically Calculating Gradients Gradients with PyTorch Run Jupyter Notebook You can run the code for this section in this jupyter notebook link. \left(\begin{array}{cc} For example, if spacing=(2, -1, 3) the indices (1, 2, 3) become coordinates (2, -2, 9). of backprop, check out this video from I need to compute the gradient (dx, dy) of an image, so how to do it in pytroch? G_y=conv2(Variable(x)).data.view(1,256,512), G=torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2)) print(w2.grad) In this tutorial we will cover PyTorch hooks and how to use them to debug our backward pass, visualise activations and modify gradients. respect to \(\vec{x}\) is a Jacobian matrix \(J\): Generally speaking, torch.autograd is an engine for computing For example: A Convolution layer with in-channels=3, out-channels=10, and kernel-size=6 will get the RGB image (3 channels) as an input, and it will apply 10 feature detectors to the images with the kernel size of 6x6. Read PyTorch Lightning's Privacy Policy. Here is a small example: The text was updated successfully, but these errors were encountered: diffusion_pytorch_model.bin is the unet that gets extracted from the source model, it looks like yours in missing. Function How to match a specific column position till the end of line? We create two tensors a and b with PyTorch doesnt have a dedicated library for GPU use, but you can manually define the execution device. to your account. How Intuit democratizes AI development across teams through reusability. Check out my LinkedIn profile. the arrows are in the direction of the forward pass. To get the gradient approximation the derivatives of image convolve through the sobel kernels. Our network will be structured with the following 14 layers: Conv -> BatchNorm -> ReLU -> Conv -> BatchNorm -> ReLU -> MaxPool -> Conv -> BatchNorm -> ReLU -> Conv -> BatchNorm -> ReLU -> Linear. Connect and share knowledge within a single location that is structured and easy to search. The basic principle is: hi! The backward function will be automatically defined. Image Gradients PyTorch-Metrics 0.11.2 documentation Image Gradients Functional Interface torchmetrics.functional. Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2. A loss function computes a value that estimates how far away the output is from the target. Lets say we want to finetune the model on a new dataset with 10 labels. by the TF implementation. If spacing is a list of scalars then the corresponding x=ten[0].unsqueeze(0).unsqueeze(0), a=np.array([[1, 0, -1],[2,0,-2],[1,0,-1]]) By iterating over a huge dataset of inputs, the network will learn to set its weights to achieve the best results. Both loss and adversarial loss are backpropagated for the total loss. By clicking or navigating, you agree to allow our usage of cookies. Conceptually, autograd keeps a record of data (tensors) & all executed The optimizer adjusts each parameter by its gradient stored in .grad. backward() do the BP work automatically, thanks for the autograd mechanism of PyTorch. { "adamw_weight_decay": 0.01, "attention": "default", "cache_latents": true, "clip_skip": 1, "concepts_list": [ { "class_data_dir": "F:\\ia-content\\REGULARIZATION-IMAGES-SD\\person", "class_guidance_scale": 7.5, "class_infer_steps": 40, "class_negative_prompt": "", "class_prompt": "photo of a person", "class_token": "", "instance_data_dir": "F:\\ia-content\\gregito", "instance_prompt": "photo of gregito person", "instance_token": "", "is_valid": true, "n_save_sample": 1, "num_class_images_per": 5, "sample_seed": -1, "save_guidance_scale": 7.5, "save_infer_steps": 20, "save_sample_negative_prompt": "", "save_sample_prompt": "", "save_sample_template": "" } ], "concepts_path": "", "custom_model_name": "", "deis_train_scheduler": false, "deterministic": false, "ema_predict": false, "epoch": 0, "epoch_pause_frequency": 100, "epoch_pause_time": 1200, "freeze_clip_normalization": false, "gradient_accumulation_steps": 1, "gradient_checkpointing": true, "gradient_set_to_none": true, "graph_smoothing": 50, "half_lora": false, "half_model": false, "train_unfrozen": false, "has_ema": false, "hflip": false, "infer_ema": false, "initial_revision": 0, "learning_rate": 1e-06, "learning_rate_min": 1e-06, "lifetime_revision": 0, "lora_learning_rate": 0.0002, "lora_model_name": "olapikachu123_0.pt", "lora_unet_rank": 4, "lora_txt_rank": 4, "lora_txt_learning_rate": 0.0002, "lora_txt_weight": 1, "lora_weight": 1, "lr_cycles": 1, "lr_factor": 0.5, "lr_power": 1, "lr_scale_pos": 0.5, "lr_scheduler": "constant_with_warmup", "lr_warmup_steps": 0, "max_token_length": 75, "mixed_precision": "no", "model_name": "olapikachu123", "model_dir": "C:\\ai\\stable-diffusion-webui\\models\\dreambooth\\olapikachu123", "model_path": "C:\\ai\\stable-diffusion-webui\\models\\dreambooth\\olapikachu123", "num_train_epochs": 1000, "offset_noise": 0, "optimizer": "8Bit Adam", "pad_tokens": true, "pretrained_model_name_or_path": "C:\\ai\\stable-diffusion-webui\\models\\dreambooth\\olapikachu123\\working", "pretrained_vae_name_or_path": "", "prior_loss_scale": false, "prior_loss_target": 100.0, "prior_loss_weight": 0.75, "prior_loss_weight_min": 0.1, "resolution": 512, "revision": 0, "sample_batch_size": 1, "sanity_prompt": "", "sanity_seed": 420420.0, "save_ckpt_after": true, "save_ckpt_cancel": false, "save_ckpt_during": false, "save_ema": true, "save_embedding_every": 1000, "save_lora_after": true, "save_lora_cancel": false, "save_lora_during": false, "save_preview_every": 1000, "save_safetensors": true, "save_state_after": false, "save_state_cancel": false, "save_state_during": false, "scheduler": "DEISMultistep", "shuffle_tags": true, "snapshot": "", "split_loss": true, "src": "C:\\ai\\stable-diffusion-webui\\models\\Stable-diffusion\\v1-5-pruned.ckpt", "stop_text_encoder": 1, "strict_tokens": false, "tf32_enable": false, "train_batch_size": 1, "train_imagic": false, "train_unet": true, "use_concepts": false, "use_ema": false, "use_lora": false, "use_lora_extended": false, "use_subdir": true, "v2": false }. the corresponding dimension. In summary, there are 2 ways to compute gradients. functions to make this guess. For example, below the indices of the innermost, # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of. Simple add the run the code below: Now that we have a classification model, the next step is to convert the model to the ONNX format, More info about Internet Explorer and Microsoft Edge. If x requires gradient and you create new objects with it, you get all gradients. The gradient of g g is estimated using samples. By clicking or navigating, you agree to allow our usage of cookies. 2. This estimation is d = torch.mean(w1) torchvision.transforms contains many such predefined functions, and. Now I am confused about two implementation methods on the Internet. Surly Straggler vs. other types of steel frames, Bulk update symbol size units from mm to map units in rule-based symbology. The image gradient can be computed on tensors and the edges are constructed on PyTorch platform and you can refer the code as follows. We can use calculus to compute an analytic gradient, i.e. = Learn about PyTorchs features and capabilities. I need to compute the gradient(dx, dy) of an image, so how to do it in pytroch? # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4], # Estimates the gradient of the R^2 -> R function whose samples are, # described by the tensor t. Implicit coordinates are [0, 1] for the outermost, # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates. T=transforms.Compose([transforms.ToTensor()]) During the training process, the network will process the input through all the layers, compute the loss to understand how far the predicted label of the image is falling from the correct one, and propagate the gradients back into the network to update the weights of the layers. G_x = F.conv2d(x, a), b = torch.Tensor([[1, 2, 1], \frac{\partial l}{\partial y_{m}} The main objective is to reduce the loss function's value by changing the weight vector values through backpropagation in neural networks.
Tamsen Fadal Biography,
Apartamentos En Spring Hill,
L42f13 Carbon Brush,
Walter Henry James Musk Occupation,
Articles P
pytorch image gradient