hiascend commited on
Commit
c311b2d
·
verified ·
1 Parent(s): 0237ca0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -19
app.py CHANGED
@@ -1,35 +1,50 @@
1
  import gradio as gr
2
- import spaces # 导入spaces时会应用torch补丁
3
  import torch
4
 
5
- spaces.zero.torch.unpatch() # 手动调用解除torch补丁方法
6
 
7
- print('cuda avaliable: ' + str(torch.cuda.is_available())) # false
 
 
 
8
 
9
- torch.set_default_device('cuda')
 
 
 
10
 
11
- zero = torch.Tensor([0]).cuda() # 报错:无GPU资源
12
 
13
- one = torch.ones(2, 2, device='cuda')
14
-
15
- two = torch.matmul(one, one).cuda()
16
-
17
-
18
- def print_device():
19
  print('cuda avaliable: ' + str(torch.cuda.is_available()))
20
- print('zero device: ' + str(zero.device))
21
- print('one device: ' + str(one.device))
22
- print('two device: ' + str(two.device))
23
 
 
 
 
24
 
25
- print_device() # cpu
 
 
26
 
27
 
28
  @spaces.GPU
29
  def greet(n):
30
- print('on zero gpu')
31
- print_device() # cuda
32
- return f"Hello {zero + n} Tensor"
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
 
35
- gr.Interface(fn=greet, inputs=gr.Number(), outputs=gr.Text()).launch()
 
1
  import gradio as gr
2
+ import spaces
3
  import torch
4
 
 
5
 
6
+ class LinearModel(torch.nn.Module):
7
+ def __init__(self):
8
+ super(LinearModel, self).__init__()
9
+ self.linear = torch.nn.Linear(1, 1, device='cuda')
10
 
11
+ def forward(self, x):
12
+ out = self.linear(x)
13
+ print('weight device: ' + str(self.linear.weight.device))
14
+ return out
15
 
 
16
 
17
+ def process():
18
+ torch.set_default_device('cuda')
 
 
 
 
19
  print('cuda avaliable: ' + str(torch.cuda.is_available()))
20
+ print('cuda device count: ' + str(torch.cuda.device_count()))
 
 
21
 
22
+ model = LinearModel().cuda()
23
+ x = torch.ones(1, device='cuda')
24
+ y = model(x)
25
 
26
+ print(model)
27
+ print(x)
28
+ print(y)
29
 
30
 
31
  @spaces.GPU
32
  def greet(n):
33
+ process()
34
+ return f"Hello {n} Tensor"
35
+
36
+
37
+ def func(n):
38
+ # step1, on cpu
39
+ process()
40
+
41
+ # step2, on gpu
42
+ res = greet(n)
43
+
44
+ # step3, on cpu
45
+ process()
46
+
47
+ return res
48
 
49
 
50
+ gr.Interface(fn=func, inputs=gr.Number(), outputs=gr.Text()).launch()