# dgl.DGLGraph.local_scope¶

DGLGraph.local_scope()

Enter a local scope context for the graph.

By entering a local scope, any out-place mutation to the feature data will not reflect to the original graph, thus making it easier to use in a function scope (e.g. forward computation of a model).

If set, the local scope will use same initializers for node features and edge features.

Notes

Inplace operations do reflect to the original graph. This function also has little overhead when the number of feature tensors in this graph is small.

Examples

The following example uses PyTorch backend.

>>> import dgl
>>> import torch


Create a function for computation on graphs.

>>> def foo(g):
...     with g.local_scope():
...         g.edata['h'] = torch.ones((g.num_edges(), 3))
...         g.edata['h2'] = torch.ones((g.num_edges(), 3))
...         return g.edata['h']


local_scope avoids changing the graph features when exiting the function.

>>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2])))
>>> g.edata['h'] = torch.zeros((g.num_edges(), 3))
>>> newh = foo(g)
>>> print(g.edata['h'])  # still get tensor of all zeros
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>> 'h2' in g.edata      # new feature set in the function scope is not found
False


In-place operations will still reflect to the original graph.

>>> def foo(g):
...     with g.local_scope():
...         # in-place operation
...         g.edata['h'] += 1
...         return g.edata['h']

>>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2])))
>>> g.edata['h'] = torch.zeros((g.num_edges(), 1))
>>> newh = foo(g)
>>> print(g.edata['h'])  # the result changes
tensor([[1.],
[1.],
[1.]])


local_var()
{"ft_lang_label":"__label__en","ft_lang_prob":0.62233543,"math_prob":0.97209126,"size":1641,"snap":"2021-43-2021-49","text_gpt3_token_len":468,"char_repetition_ratio":0.14660965,"word_repetition_ratio":0.12448133,"special_character_ratio":0.35161486,"punctuation_ratio":0.28457448,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9922393,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-27T20:18:42Z\",\"WARC-Record-ID\":\"<urn:uuid:932a14ac-83e8-44c8-b4fe-890b5283c83f>\",\"Content-Length\":\"22904\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5d645d29-68f1-4f8f-94c0-fd6a0ea55f31>\",\"WARC-Concurrent-To\":\"<urn:uuid:735f3723-5ccb-4f8a-86af-9de1e45417cf>\",\"WARC-IP-Address\":\"99.83.245.140\",\"WARC-Target-URI\":\"https://docs.dgl.ai/en/0.7.x/generated/dgl.DGLGraph.local_scope.html\",\"WARC-Payload-Digest\":\"sha1:ES4PHWJWU33DGQT5COIVRDBRROIEPXAU\",\"WARC-Block-Digest\":\"sha1:DOJWQB5VEBSOHWMKRVCGOXNOCERVESOR\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323588242.22_warc_CC-MAIN-20211027181907-20211027211907-00426.warc.gz\"}"}