반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

AWS Deepracer Forum Q&A

2019. 7. 8. 05:49 | Posted by 솔웅


반응형

6월 AWS Deepracer Virtual Race에 참가하기 위해 자율주행을 위한 인공지능 모델을 훈련 시키면서 생겼던 질문을 AWS Deepracer Forum에 몇번 올렸었다.

 

https://forums.aws.amazon.com/forum.jspa?forumID=318 

불러오는 중입니다...

 

도움이 되는 답변들이 있어서 여기에 정리해 둔다.

 

https://forums.aws.amazon.com/thread.jspa?threadID=304352&tstart=0

불러오는 중입니다...

첫번째 질문은 Action Space와 Hyperparameter에 대한 것이었다.

 

What is good Action Space and Hyperparameter for Kumo Torakku track?

Posted by: Changsoo

Posted on: Jun 6, 2019 5:13 AM

 

 

I've created a model for Kumo Torakku track and got 26 seconds lap time.
Actually the model was cloned from others. (Straight Track -> Oval Track -> London Loop).

Repetition of training does not reduce lap time.

I used hyperparameter as default and changed the Maximum speed to 5 in Action Space.
(Others are as default. Steering 30, Steering angle granularity 5, Speed granularity 2)

Since I'm familiar with coding, I tried multiple things with reward_function.
i.e. distance from center, all wheels on track, steering threshold, speed penalty etc.

As I said, there is no improvement at all with this configuration for Kumo Torakku.

So I will create new Model.

Anybody recommend any Action Space configuration for Kumo Torakku to get better results please?

Maximum steering angle :
Steering angle granualrity :
Maximum speed :
Speed granuality :

I have read documents for Hyperparameters but no idea what those are. ;(
Anybody can recommend good Hyperparameters configuration for Kumo Torakku please?

 

 

아래는 이 질문에 대한 답변들....

 

Re: What is good Action Space and Hyperparameter for Kumo Torakku track?

Posted by:  DeClercq-AWS

Posted on: Jun 10, 2019 11:12 PM

 in response to: Changsoo

 

Hyperparameters directly impact how the model is updated, they control the settings of the optimization algorithm that is used to "solve" for the model that gives the maximum expected cumulative return. Changing hyperparameters can improve the convergence of the model, or worsen it. For example, if you increase the learning rate, the weights in your neural network will update with larger increments. The model may improve (train) faster but the risk is that you miss the optimal solution, or the model never converges as updates are too large. Finding good hyperparameters often required trying a number of different combinations and then evaluating the performance of the model vs time spent training or some other metric. For example, I am busy training a 3m/s model (with 2 speed granularity) using a learning race of 0.001 and a low number of epochs. I can see during training at around 90 minutes my model is starting to do a lap now and then. If the learning rate was smaller, it would probably take longer for my model to complete a lap.



Hyperparameters는 모델이 업데이트되는 방식에 직접적으로 영향을 주며, 최적화 알고리즘의 세팅을 컨트롤 합니다. 이는 기대되는 누적된 return의 최대치를 주도록 모델에 대한 'solve'에 사용됩니다. Hyperparameters를 변경하면 모델의 수렴성이 향상되거나 악화 될 수 있습니다. 예를 들어, learning rate를 높이면 신경망의 weights가 더 큰 폭으로 증가하게 됩니다. 모델이 더 빠르게 향상 될 수는 있지만 최적의 솔루션이 누락되거나 업데이트가 너무 많아서 모델이 수렴하지 않을 위험이 있습니다. 훌륭한 Hyperparameters를 찾는 일은 종종 여러 가지 조합을 시도한 다음 모델의 퍼포먼스, 트레이닝 시간이나 다른 메트릭 등을 비교하면서 평가합니다.  예를 들어, 나는 0.001의  learning race와 낮은 epochs 수를 사용하여 3m / s 모델 (2 speed granularity)을 훈련 중입니다. 나는 약 90 분 후에 현재의 lap에 도달 하는 것을 경헙했습니다. 만약 learning rate가 더 낮 으면 내 모델이 lap에 도달할 때까지 더 오래 걸릴 것입니다.

 

Note that at 3m/s my model will not be as fast as a converged 5m/s (or faster) model, but those will take a long time to converge. We increased the training speed in the console to a max of 8 m/s. Training at speeds faster than 8m/s tends to send the model spinning off the track.



3m / s에서 내 모델은 converged 된 5m / s (또는 더 빠른) 모델만큼 빠르지는 않을 것이지만,  5m/s (or faster) model은 converged 하는데 오랜 시간이 걸릴 것입니다. 우리는 콘솔의 교육 속도를 최대 8 m / s로 높였습니다. 8m / s보다 빠른 속도로 훈련하면 트랙에서 모델이 회전하는 경향이 있습니다.



Kind regards

 


De Clercq

 

 

 

 

 

Re: What is good Action Space and Hyperparameter for Kumo Torakku track?

Posted by:  DeClercq-AWS

Posted on: Jun 11, 2019 10:46 AM

 in response to: Changsoo

 

Hi Changsoo

 

I did the following tests overnight to show impact of hyperparameters

나는 지난 밤에 hyperparameters의 영향을 보기 위해 다음과 같은 테스트들을 진행했습니다.
 

Trained 4 models on the Kumo Torakku training, each for 180 minutes, using my own reward function that does some center line following, scales reward for driving fast etc. 



Kumo Torakku 트랙에서 4개의 모델을 훈련 시켰습니다. 각각의 훈련 시간은 180분 입니다. reward function은 제것을 사용했습니다. 여기에느느 중앙선 따르기, 빠르게 드라이브하기 등에 reward를 주는 로직등이 있습니다.

I alternated
 

Model 1: 3 m/s 2 speed granularity with learning rate = 0.001 and epochs = 3
Model 2: 3 m/s 2 speed granularity with default hyperparameters
Model 3: 5 m/s 2 speed granularity with learning rate = 0.001 and epochs = 3
Model 4: 5 m/s 2 speed granularity with default hyperparameters

Doing 5 lap evaluation on Kumo Torakku training, showing lap completion percentages

Kumo Torakku 트랙에서 5 lap evaluation을 진행했으며 lap completion percentages는 다음과 같습니다.

Model 1: 100% 100% 100% 100% 100%
Model 2: 46% 67% 61% 100% 62%
Model 3: 70% 58% 100% 100% 100%
Model 4: 63% 88% 100% 36% 27%


This shows you the impact of playing with the hyperparameters.

이 예에서 당신은 hyperparameters가 주는 영향을 보실 수 있을 겁니다.

Kind regards

De Clercq

 

 

 

Re: What is good Action Space and Hyperparameter for Kumo Torakku track?

Posted by: Amazon Customer

Posted on: Jun 14, 2019 10:48 AM

 in response to: Changsoo

 

I copied all these waypoints out from the kumo log if it helps anyone.

https://gist.github.com/joezen777/98daa6496acf6a6df3269f253f9388f9

 

Draw Kumo Map

Draw Kumo Map. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

Re: What is good Action Space and Hyperparameter for Kumo Torakku track?

Posted by:  DeClercq-AWS

Posted on: Jun 14, 2019 4:21 PM

 in response to: Amazon Customer

 

Hi


To get the waypoints you can download the track's .npy file and use the code in the log-analysis workbook to extract them 



 

Log-analysis is here

https://github.com/aws-samples/aws-deepracer-workshops/tree/master/log-analysis

 

Track npys are here

https://github.com/aws-samples/aws-deepracer-workshops/tree/master/log-analysis/tracks

 

See breadcentric's blog on how to use log-analysis (link is in the Pit Stop page)

https://aws.amazon.com/deepracer/racing-tips/

 

Kind regards

De Clercq

 

 

 

Re: What is good Action Space and Hyperparameter for Kumo Torakku track?

Posted by: cladeira

Posted on: Jun 23, 2019 1:52 PM

 in response to: DeClercq-AWS

 

Hi @DeClercq-AWS,

 

I'm using your script, but i have a couple of questions:

 

1- Are Yaw and Steering on Degrees or Radians? It seems to be in Radians.

2- How can we include other parameters?

3- It seems Track Width is not returning the right value. How can we confirm?

4- Is Progress defined from 0-1 or 0-100? It seems it's based on 0-1, but the documentation says 0-100.

 

Thanks,

cladeira

 

 

 

 

두번째 질문은 reward_function으로 속도를 높이는 데 대한 질문이었다.

 

 

updated reward function to speed up but not working as expected.

Posted by: Changsoo

Posted on: Jul 2, 2019 11:24 AM

 

Hi

I updated reward_function to speed up using params but not working as expected.

 

The reward_function is this

 

=====================================

def reward_function(params):

'''

Example of rewarding the agent to follow center line

'''

reward=1e-3

# Read input parameters

track_width = params

distance_from_center = params

steering = params

speed = params

all_wheels_on_track = params

steps = params

progress = params

# Total num of steps we want the car to finish the lap, it will vary depends on the track length 



TOTAL_NUM_STEPS = 300

if distance_from_center >=0.0 and distance_from_center <= 0.03:

reward = 1.0

if not all_wheels_on_track:

reward = reward -1

else:

reward = reward + progress

# add speed penalty

if speed < 1.0:

reward *=0.80

else:

reward += speed

# Give additional reward if the car pass every 100 steps faster than expected

if (steps % 50) == 0 and progress > (steps / TOTAL_NUM_STEPS) :

reward += 10.0

return float(reward)

 

==================================================

 

There was no lines with bold in previous model.

 

I trained for 5 hours but the result is slower than before.

 

with Previous model, I could get 21~24 seconds to run the Empire City track but with the new model after training for 5 hour, I am getting 24~27 seconds. 



 

Other Action space and hyperparameters are same.

 

Anybody knows why the result is slower than before?

 

 

 

  Re: updated reward function to speed up but not working as expected.

Posted by:  ETAGGEL

Posted on: Jul 3, 2019 1:51 AM

 in response to: Changsoo

 

Hi,

 

You could insert some debug code to ensure it is getting applied, e.g. print("Fast reward bonus given"). 



디버그를 위한 코드를 넣어서 해당 부분이 제대로 적용되는지를 살펴 보실 수 있습니다.  e.g. print("Fast reward bonus given").
 

However, looking at your code, I think the issue is that progress is a value from 0-100, where as your steps / TOTAL_NUM_STEPS gives a fraction 0-1. So progress will nearly always be greater than that, and so your bonus is probably being given regardless of actual performance. 



코드를 살펴보면 progress는 0-100 사이의 값이며, steps / TOTAL_NUM_STEPS는 0에서 1 사이의 fraction이 됩니다. progress는 항상 steps / TOTAL_NUM_STEPS 보다 더 높을 것이므로 실제 퍼포먼스에 상관없이 reward가 주어지는 것 같습니다. 

I'm also not sure that a bonus of 10 every 50 steps would be enough to encourage the model to favour those actions. It would also depend on your discount rate, e.g. if you're using the default discount rate of 0.9 then that only equates to 10 steps look ahead, so your bonus would be invisible to most policy training updates. 



50 단계마다 10 씩 보너스가 주어지면 모델이 그 행동을 선호하도록 장려하기에 충분하지 않을 것입니다. 이것은 당신의 discount rate에 따라 그 영향이 달라 질 수 있습니다. e.g. 디폴트 discount rate인 0.9를 사용하는 경우 10 steps를 앞당겨 look ahead 하므로 보너스는 대부분의 정책 교육 업데이트에서 볼 수 없습니다.

Finally, you need to be careful of overfitting your model to the track. When that happens, lap times can get worse as the model learns the safer actions/track position to ensure more stability. So that might explain why your model got slower, even if your reward wasn't correctly being applied. 



 마지막으로 해당 트랙에 모델을 너무 많이 맞추는 것에 조심해야 합니다. 이러한 상황이 발생하면 모델이 안정성을 위해 좀 더 안전한 액션과 트랙 위치를 배우게 되어 랩 타임은 오히려 악화 될 수 있습니다. 따라서 보상이 올바르게 적용되지 않은 경우에도 모델이 왜 느려 졌는지 설명 할 수 있습니다.

Lyndon

 

 

 

https://github.com/aws-samples/aws-deepracer-workshops/blob/master/Workshops/2019-AWSSummits-AWSDeepRacerService/Lab1/Readme-Korean.md

 

aws-samples/aws-deepracer-workshops

DeepRacer workshop content. Contribute to aws-samples/aws-deepracer-workshops development by creating an account on GitHub.

github.com

 

반응형


반응형

6월에 열린 아마존 AWS Deepracer Virtual Race #2 에서 20.695초 104등을 차지했다.

총 참가자 수는 572명이다.

 

 

나는 Sofia와 Dalyo 두 종류의 모델을 훈련 시키고 있다. 

이번 대회에서는 주로 Sofia를 출전 시키다가 나중에 Dalyo를 출전 시켰다.

최고 점수는 Dalyo로 따냈다.

 

Sofia와 Dalyo 두 모델의 근본적인 차이점은 Action Space 였다.

 

Sofia Action Space

Dalyo Action Space

Sofia는 최고 스피드를 5로 했고 Dalyo는 최고 스피드를 8로 했다.

아무래도 최고 스피드를 더 높게 만든 Dalyo가 더 성적이 좋게 나온 것 같다.

처음에는 Sofia가 안정적이라서 계속 참가를 시켰다.

Dalyo는 거의 완주를 못 했었다. 아마 속도가 너무 빨리서 트랙을 벗어나는 경우가 많았나 보다.

 

나중에 좀 더 연습을 시켜서 Dalyo의 완주율이 50% 정도 올랐다. 

그 완주한 점수들이 Sofia 모델보다 훨씬 높아서 결국 최고 점수는 Dalyo가 차지 했다.

 

이 Action Space는 최초 모델을 만들 때 정해주고 그 다음에는 수정이 불가능 하게 돼 있다.

 

그래서 이 Sofia와 Dalyo를 훈련 시킬 때는 주로 reward_function을 수정해 가면서 성능 향상을 시키려고 노력했다.

 

Sofia는 거의 10번 훈련 시켰었는데 처음 Sofia를 탄생 시켰을 때의 reward_function은 다음과 같다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    
    # Calculate 3 markers that are at varying distances away from the center line
    marker_1 = 0.1 * track_width
    marker_2 = 0.25 * track_width
    marker_3 = 0.5 * track_width
    
    # Give higher reward if the car is closer to center line and vice versa
    if distance_from_center <= marker_1:
        reward = 1.0
    elif distance_from_center <= marker_2:
        reward = 0.5
    elif distance_from_center <= marker_3:
        reward = 0.1
    else:
        reward = 1e-3  # likely crashed/ close to off track
    
    return float(reward)

 

이 때의 트랙은 직선 트랙이었다.

그래서 중앙선에 가까운 경우 reward를 주는 로직을 만들어서 훈련 시켰다.

 

두번째도 Straigh track인데 함수를 조금 바꿨다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 15

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 2.5:
        reward *=0.80
    
    return float(reward)

 

완전 Stupid 한 script 이다.

추가한 부분에 reward = reward+n 이런식으로 reward가 더해지거나 빼지는 방식으로 스크립트를 작성했어야 했는데 멍청하게도 그냥 reward 값을 그냥 대입하는 방식으로 돼 있다.

 

위에 보면 차량이 center로 부터 0.03 이상 떨어지지 않으면 reward를 1.0으로 설정하고 그 다음에 트랙 안에 있지않으면 reward = reward-1을 해야 하는데 그냥 reward=-1을 해 버렸다.

reward=params['progress']도 reward=reward+['progress']로 했어야 했다.

 

하여간 이러한 실수가 이 후에도 계속 됐고 후반부에 가서야 이것이 잘 못 됐다는 걸 발견 했다.

 

위 스크립트에서는 distance_from_center 부분은 아무런 역할을 하지 않는 부분이 돼 버렸다.

 

세번째는 Oval Track에서 훈련 시켰고 네번째는 London loop에서 훈련 시켰다.

 

 

 

다섯번 째 부터 6월 대회에서 사용했던 Kumo Torakku Track에서 훈련 시켰다.

그리고 Dalyo라는 새 모델도 만들었다.

 

이 때부터 Sofia와 Dalyo 두 모델을 훈련 시켰지만 Sofia가 대부분 완주를 하고 Dalyo는 그렇지 못했기 때문에 계속 Sofia만 출전 시켰었다.

 

Sofia는 이후 10여번 훈련 시켰고 Dalyo는 4번 정도 더 훈련 시켰다.

 

Sofia의 Kumo Torakku 트랙의 마지막 reward_function은 이렇다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # add speed penalty
    if speed < 1.0:
        reward *=0.80
    else:
        reward += speed
    
    return float(reward)

 

speed를 좀 더 빨리 하기 위해 reward에 현재의 스피드를 더하는 로직을 사용했다.

근데 별 효과는 없었다.

 

Dalyo의 Kumo Torakku 트랙 마지막 reward_function도 똑 같다.

 

이 Virtual 경기 대회는 횟수에 상관없이 계속 모델을 참가 시킬 수 있기 때문에 (30분 간격으로) 나중에는 완주 횟수는 떨어지지만 점수가 더 높게 나오는 Dalyo 모델을 주로 출전 시켰고 결국은 104 등을 기록 했다.

 

 

7월에는 3번째 Virtual 대회가 열리고 1번의 offline 대회가 뉴욕에서 열릴 예정이다.

트랙은 둘 다 Empire City 트랙.

가능하면 둘 다 참가할 계획이다.

 

6월 Virtual 대회를 참가하면서 배운 것은 두가지

1. reward_function을 바꾼 후 당초 예상대로 그 변경 내용이 적용 되는지 확인 하는 것이 필요하다.

   AWS의 Debugging 툴을 활용해서 확인 해야 겠다.

2. 훈련을 위해 사용 되는 3가지 주요 세팅 중 Hyperparameter 를 활용한 성능 향상 방법을 배워야 겠다.

 

Action Space는 최초 모델을 생성할 때 설정하고 그 이후에는 변경이 불가능 하다.

reward_function과 Hyperparameter는 변경 가능한데 지금까지는 reward_function만 변경하면서 훈련 시켰다.

 

Hyperparameter는 잘 몰랐기 때문이다.

이제 Hyperparameter를 공부해서 이 부분도 모델 성능 향상에 활용해야 20초 대를 넘을 수 있을 것 같다.

 

 

이번 Empire City 트랙을 사용하는 Virtual Circuit에서는 15초대 진입과 50등 이내로 돌입하는 것을 목표로 참가할 계획이다.

 

화이팅!!!!!!!!!!!!

반응형

MEGAZONE CLOUD AWS DeepRacer League in Korea

2019. 6. 25. 22:23 | Posted by 솔웅


반응형

메가존 클라우드 AWS Deepracer League가 개최 됩니다.

 

참가 신청은 이곳에서 하실 수 있네요.

 

https://www.megazone.com/deepracer_league_01/ 

 

제1회 메가존 클라우드 AWS DeepRacer 리그 참가 신청

Asia-Pacific & KOREA, No.1 AWS Premier Consulting Partner 메가존 클라우드가 제1회 AWS DeepRacer 대회를 개최 합니다.

www.megazone.com

1등 상금이 100만원에 라스베가스 re:Invent 왕복 항공권 및 숙박권...... 와우....

 

AWS DeepRacer 차량 모델이 있으신 분은 참가하시면 좋겠네요.

(관계자 분이 확인해 주셨는데 DeepRacer 차량이 없어도 된답니다. 관심 있으신 분들은 일단 가셔서 주최측에 있는 차량을 이용해서 참가 하실 수 있답니다.)

 

제가 사는 곳은 조그만 동네라서 차량을 트랙에서 직접 테스트 해 볼 기회를 갖기 무척 힘듭니다.

한국에 계신 분들은 아주 좋은 기회인 듯 합니다.

 

참가하셔서 좋은 결과 있으시길 바랍니다.

 

 

Asia-Pacific & KOREA, No.1 AWS Premier Consulting Partner 메가존 클라우드가 AWS DeepRacer 리그를 개최 합니다.

 

실제 트랙이 설치되어 참가자가 직접 제작한 모델을 실제 차량(Agent)으로 주행 가능하며, 우승 시 상금 외 미국 re:Invent 기간 왕복 항공 및 숙박권이 주어지오니, 많은 신청 부탁 드립니다.

 

  • 대회명 : MEGAZONE CLOLUD Circuit Challenge
  • 대회 일자 : 2019년 7월 4일 (목)
  • 대회 장소 : 신도림 쉐라톤서울 디큐드시티호텔 6층 그랜드볼룸 [약도]
  • 대회 시간 : 오전 10시 ~ 오후 05시
  • 시상
    – 1등 : 상금 100만원 + re:Invent 왕복 항공 및 숙박권
    – 2등 : 상금 50만원
    – 3층 : 상금 30만원
  • 참가 자격 : 직접 제작한 AWS DeepRacer 모델을 보유한 사람

 

메가존 클라우드와 함께 세계 신기록에 도전해 보세요. [세계 기록 보기]

※ 본 리그는 메가존 클라우드가 자체적으로 진행하는 행사로 AWS에서 개최하는 리그와 무관합니다.
※ 상금 및 경품 지급 시 소득세 등 제세공과금이 차감 혹은 청구 됩니다.
※ 본 경기 규칙은 AWS DeepRacer League 규칙을 따르며 트랙 또한 re:Invent 2018 트랙에서 진행 됩니다.

 

========================================

 

저는 AWS Deepracer 모델 차량을 7월 중순에 받을 예정이라서 10월 3일 토론토에서 열리는 경기에 참가할 수 있을 것 같습니다.

 

휴가 내고 비행기 타고 가서 참가할 생각인데.... 

어떻게 될 지 아직...... 

 

지금 제가 만들고 있는 모델은 Kumo Torakku 트랙에서 23초를 기록하고 그 이후에는 전혀 기록이 나아 지질 않고 있습니다.

지금 1,2,3 등은 모두 10초 대 이던데.... 그런 기록은 어떻게 하면 낼 수 있을 지.......

 

3등은 Kimwooglae인걸로 봐서 한국분인것 같네요.

 

 

어떻게 연락해서 방법 좀 배울 수 없을까?

 

혹시 AWS Deepracer 공부하는 커뮤니티 있으면 알려 주세요.

혼자 공부하는 것 보다 서로 경험 공유하면서 배우면 훨씬 좋을 것 같습니다.

 

 

반응형


반응형

테슬라 주식이 최근 한참 빠졌다.

 

작년까지만 해도 생산이 제대로 안 된다는게 계속 발목을 잡았는데 올해 들어와서는 주문량 감소와 financial 이슈가 폭락을 이끌고 있다.

 

주문량 감소는 2018년 4/4분기와 비교했을 때 2019년 1/4분기 주문량이 줄었다는 건데....

글쎄 내 생각엔 전기차에 대한 수요 욕구는 점점 더 증가할 것이라고 판단하고 있다. 그래서 이게 그렇게 주가 폭락의 근본 원인이 될 수 있나? 하는 의문이 든다.

오히려 주문은 느는데 테슬라가 밧데리 물량이 확보 안된다든지 해서 미처 생산을 제대로 못하고 있어서 주가에 악영향을 주고 있는 상황이 오면 더 이해할 수 있겠다.

 

그리고 financial 이슈는 자금 부족 문제는 있을 수 있지만 그렇다고 테슬라가 망하거나 하는 상황은 가지 않을 것이라고 생각한다.

 

그래서 이 악재도 이렇게 까지 주가가 폭락 할 충분한 이유는 아니라고 본다.

 

내가 생각하는 테슬라 혹은 전기차 시장의 악재는 미국의 세일가스 라고 본다.

 

미국이 사우디를 제치고 석유 생산 세계 1위를 하도록 만든게 세일가스이다.

미국은 앞으로 이 세일가스를 계속 팔아야 된다.

그러면 앞으로 상당기간 내연 기관 차량이 이를 소비하는 한 구성 요소로 존재하는게 더 좋다.

 

이 이유가 미국 정부가 전기차의 부흥을 도와주는 정책을 세우지 않도록 만들고 있다고 본다.

 

하지만 그렇더라도 전기차의 수요는 점차 늘어날 것이고 메이저 기업들의 전기차 생산 설비 확산은 점점 더 광범위하게 일어날 것이라고 본다.

 

메이저 차량 회사들이 기존 내연기관 관련 인력을 감축하고 있는 것도 그러한 이유에서 일 것이다.

 

하여간 길게 글을 쓸 필요는 없을 것 같고 내 생각에 지금 테슬라 주가의 폭락은 과하다고 본다.

악재라고 얘기하는 것들은 일시적인 사안들이라고 본다.

더군다나 그 악재로 이렇게까지 폭락할 정도도 아니고....

 

2분기 실적 발표를 기점으로 크고 긴 상승 국면으로 전환하지 않을까 예측해 본다. (솔직히 그렇게 기대해 본다)

 

이런 나의 기대에 조금 더 힘을 보태주는 기사가 있어서 번역해 봤다.

 

 

 

Tesla Stock in 2019 Looks a Lot Like Netflix Stock in 2011

By Eddie YoonJune 4, 2019 5:30 a.m. ET

 

 

Tesla stock continues to drop, and has now fallen to roughly half its peak of $385. This is bad, but it is nowhere as bad as Netflix ’s 80% stock decline in 2011. Netflix’s decline was followed by an eight-year stretch of growth. Will Tesla shareholders be similarly rewarded? The question is whether Netflix’s 2011 is a comparable proxy for Tesla’s 2019.

 

테슬라 주가는 계속 하락세를 보이고 있으며, 지금은 이전 최고치 인 $ 385의 절반 정도로 하락했다. 안 좋은 주가이다, 하지만 2011 년 Netflix의 주가가 80 % 폭락한 정도는 아니다. 이 Netflix의 폭락 이후 넷플릭스는 8년간의 지속적인 성장을 보인다. 테슬라 주주들도 마찬가지로 보상받을 것인가? 문제는 Netflix의 2011 년이 테슬라의 2019 년과 비슷한 상황인지 아닌지다.

 

 

Back in 2011, Netflix had announced a jarring price increase, and CEO Reed Hastings announced it was separating its streaming business from its DVD by mail business. In a single quarter, Netflix lost 800,000 subscribers—just over 3% of its subscribers, then sitting at 24 million.

 

2011 년으로 돌아가서, 당시 Netflix는 (약간 분위기에 안 맞게) 가격 인상을 발표했으며, CEO인 Reed Hastings는 스트리밍 사업을 우편을 통해 DVD 를 배달하는 사업과 분리한다고 발펴했다. 당시 1 분기만에 넷플릭스는 총 가입자 수의 3 %를 상회하는 80 만 명의 가입자를 잃어 총회원수가 2400 만명이 되었다.

 

 

At the core of those costly decisions was the company’s belief in their category. They believed that streaming was the future and had a significant upside. And Netflix was 100% right. Now they have 60 million households in the U.S. and 150 million worldwide. The stock price is 39 times higher than its low point in 2011.

 

당시 리스크가 많은 이 결정의 핵심은 회사의 카테고리에 대한 믿음이었습니다. 그들은 스트리밍이 미래라고 믿었고 실제로 그 결정이 상승의 기폭제가 되었다. Netflix의 예상과 결정이 100 % 들어 맞은 것이다. 넷플릭스는 현재 미국에 6000 만 가구, 전 세계에 1 억 5000 만 가구를 회원으로 두고 있다. 주가는 2011 년 저점보다 39 배 상승했다.

 

 

Similarly, Tesla is spot on in their belief that demand for electric vehicles will grow exponentially. In 2018, electric vehicles were 2% of total new cars sold in the U.S. but 20% of Americans want an electric vehicle (per a study by AAA). Electric vehicles already have roughly a 10% market share in California. Tesla accounts for more than 60% of the share of growth of electric cars. The idea that Tesla’s 30,000 dip in deliveries in Q1 2019 versus Q4 of 2018 highlights a fundamental demand problem with either electric vehicles (which could easily number in the millions in the near future) or Tesla itself (since their products are beloved by consumers) seems like a stretch.

 

이와 비슷하게, 테슬라는 전기 자동차에 대한 수요가 기하 급수적으로 늘어날 것이라는 믿음을 가지고 있다. 2018 년 전기 자동차는 미국에서 판매 된 총 신차의 2 %를 기록하고 있지만 미국인의 20 %는 전기 자동차를 원하는 것으로 알려져 있다. (AAA에 의한 연구 당). 전기 자동차는 이미 캘리포니아에서 약 10 %의 시장 점유율을 가지고 있습니다. 테슬라는 전기 자동차의 성장 점유율의 60 % 이상을 차지합니다. 2018년 4사분기와 비교했을 때 2019년 1사분기의 차량 판매량이 3만대 줄어든 것은 근본적인 수요 이슈를 부각 시켰습니다. 즉 가까운 미래에 수백만에 다다를 것으로 생각되는 전기차 사업 혹은 테슬라 그 자체이든 시장은 확대 될 것이라는 것입니다. (테슬라의 제품은 고객들로 부터 사랑을 받고 있습니다.)

 

 

 

Netflix also believed in their pricing power, especially if they continued to improve their product (e.g., better recommendations and more content, including original, award-winning content). Netflix was also correct about this, and has continued to raise prices successfully. Even though Netflix has surely lost some subscribers as they’ve raised prices, total revenue and profits have grown enough to offset those losses.

 

Netflix는 또한 pricing power를 믿었습니다. 특히 제품 개선을 지속하는 경우 (예 : 더 나은 추천 기능이나 좀 더 많은 - 오리지널 이거나 수상경력이 있는 - 콘텐츠 등) pricing power는 더욱 증가할 것이라고 믿었습니다. Netflix의 이 예측도 들어 맞았습니다. 그 결과 그들은 지속적으로 가격을 올리는데 성공했습니다. 가격 인상으로 일부 고객을 잃은 것은 사실이지만 그들은 가격을 인상함으로서 총 매출과 수익은 그 손실을 상쇄하기에 충분했습니다. 

 

 

Tesla hasn’t increased its prices, but did see the $7,500 federal rebate for electric vehicles halved at the end of 2018—just at the same time their delivery volume dropped. Some analysts connected these two dots and see weakness in demand for Teslas. The more likely scenario is that this temporary price shock impacted quarterly sales by pulling some Q1 2019 sales earlier into Q4 2018 since the federal tax rebate phase-out was known for some time.

 

테슬라는 가격을 인상하지 않았지만 2018 년 말에 전기 자동차에 대한 7,500 달러의 연방 환급액이 절반으로 줄었습니다. 같은 기간 테슬라의 delivery 볼륨도 줄었습니다. 일부 분석가들은 이 둘을 근거로 Teslas에 대한 수요 약세로 보았습니다. 하지만 가장 그럴듯한 시나리오는 이러한 연방 세금 환급이 사라질 것이라고 알려져 그 이전인 2018년 1사분기의 수요를 증가시켰고 이는 2019년 1사분기 수요를 미리 끌어 당겼기 때문에 위와 같은 결과 - 2019년 1/4분기 매출이 3만대 감소- 가 나왔다는 겁니다.

 

 

The reality is that Tesla’s pricing power is strong. The best evidence of Tesla’s pricing power is that Tesla is attracting mainstream car owners as well as other luxury brand owners. Per CEO Elon Musk, the five most commonly traded in cars for a Tesla are Honda Accord, Honda Civic, Toyota Prius, Nissan Leaf, and BMW 3 series. It is no coincidence that from 2016 to 2018 Toyota Prius, Toyota Camry, Honda Accord, and Honda Civic all decreased a collective 15% in the US. This decline of nearly 190,000 cars is comparable to the over 180,000 Teslas sold in the US in 2018.

 

현실은 테슬라의 가격 결정권이 강하다는 것이다. 테슬라의 가격 결정력에 대한 가장 좋은 증거는 테슬라가 다른 럭셔리 브랜드 뿐만 아니라 주류 자동차 소비자를 끌어 들이고 있다는 것입니다. CEO 인 엘론 머스크 (Elon Musk)에 따르면 테슬라가 일반적으로 대체하는 5개의 차량은 혼다 어코드, 혼다 시빅, 토요타 프리우스, 닛산 리프, BMW 3 시리즈 등 입니다. 2016 년부터 2018 년까지 Toyota Prius, Toyota Camry, Honda Accord 및 Honda Civic의 판매량이 미국에서 15 % 감소했습니다. 차량 대수로는 약 19 만대의 감소한 것입니다. 이것은 2018 년에 미국에서 판매 된 180,000 대가 넘는 테슬라의 판매 대수와 비슷합니다.

 

 

Netflix and Tesla have also both struggled in some of the same ways, namely communication and execution.

 

Netflix와 Tesla는 communication and execution이라는 측면에서 비슷한 방식으로 어려움을 겪었습니다. 

 

 

Even though Netflix was ultimately right to increase prices and focus on streaming, it was clumsy in how it communicated these changes to customers. The timing of some of these moves was also off: it could have allowed DVD by mail to slowly fade, and introduced its price hike when it launched House of Cards, its first major success in original content. These were unforced errors. Similarly, Tesla has had similar, self-inflicted struggles on communication and execution.

 

넷플 릭스가 궁극적으로 가격을 올리고 스트리밍에 집중하는 것이 옳았지 만 이러한 변화를 고객에게 어떻게 전달했는지는 서툴 렀다. 이러한 움직임의시기는 또한 벗어났습니다. 우편으로 DVD를 배달하는 서비스를 좀 더 천천히 사라지도록 할 수 있었고 원본 콘텐츠로 첫번째 메이저급 성공을 거둔 House of Cards의 상영이 시작됐을 때 가격 상승을 발표할 수도 있었다. 즉 발표 타이밍에서 서툴렀다는 것이다. 이것은 자체적인 오류라고 할 수 있다. 비슷하게, 테슬라는 communication and execution 에 있어 자초한 어려움을 비슷하게 겪고 있다.

 

 

The difference between the two firms is that since those earlier stumbles, Netflix’s execution has gotten smoother and their communication more empathetic. Netflix has continued to raise prices, using a good/better/best pricing strategy to give customers a feeling of control. Netflix has also recognized that it’s costly to try and be great at everything; this is why they’ve migrated to Amazon Web Services, even though Amazon Prime Video is a direct competitor. They’ve managed to focus on improving and expanding their content and geographies.

 

두 회사의 차이점은 넷플 릭스의 사태가 더 일찍 일어 났으므로 넷플 릭스의 execution이 좀 더 원활해졌고 communication은 좀 더 공감을 얻었다는 겁니다. Netflix는 고객에게 고객 자신이 가격을 컨트롤 하고 있다는 느낌을 주기 위해 good/better/best라는 가격 정책을 사용하면서 가격을 인상했습니다. Netflix는 또한 모든 것에서 최고가 되려고 하는 것이 너무 많은 비용을 초래한 다는 것을 깨달았습니다. 그렇기 때문에 Amazon Prime Video가 직접적인 경쟁자 임에도 불구하고 Amazon Web Services로 마이그레이션 한 이유입니다. 그들은 콘텐츠를 개선하고 서비스 지역을 확장하는데 초점을 맞춰서 사업을 진행했습니다. 

 

 

Meanwhile, Tesla seems to be trying to do too many things at once, perhaps one reason they are struggling on deliveries. Musk continues to juggle roles across Tesla, Space X, and the Boring Company, and to occasionally issue SEC-incensing tweets.

 

그 사이에, Tesla는 한꺼번에 너무 많은 것을 시도하고있는 것처럼 보인다, 아마 납품에 어려움을 겪고 있는 것도 한 이유일 것이다. 머스크는 테슬라, 스페이스 X, the Boring Company에서 계속 자신의 역할을 수행하고 있다. 그리고 때때로 SEC를 건드리는 트윗도 하고 있다. 

 

 

While Tesla is right about consumer demand and their pricing power, they should also remember that a successful company takes more than that. Being right isn’t always enough.

 

테슬라의 소비자 수요와 가격 결정력에 대해서는 옳다고 생각하지만 성공적인 기업은 그 이상을 필요로한다는 것을 기억해야합니다. 옳다는 것이 항상 충분한 것은 아닙니다.

 

Eddie Yoon is the founder of EddieWouldGrow, a think tank and advisory firm on growth strategy, and the author of the book Superconsumers and a monthly newsletter. Find him on Twitter and Instagram @eddiewouldgrow.

반응형


반응형

AWS DeepRacer League

 

누구나 이용할 수있는 세계 최초의 자율주행 레이싱 리그에 오신 것을 환영합니다.

re:Invent 2019에서 AWS DeepRacer Cup에서 우승해 상금, 영예, AWS DeepRacer Championship Cup을 획득하세요. 매월 열리는 가상 Circuit 레이스에서 온라인으로 경쟁하거나 전 세계 Summit Circuit 경주 행사에서 직접 경쟁 할 수 있습니다.

 

Standings: Check out the live leaderboard and latest race results

view Leaderboards >>

 

AWS DeepRacer console을 통해 가상공간에서 레이스

현재 진행 중인 레이스 - Kumo Torakku

 

일본의 스즈카 트랙에서 영감을 얻은 Kumo Torakku 서킷 레이싱에서 우승해 re:Invent로 가는 경비 지원을 받으세요.  후지산을 보며 도쿄의 거리를 달려 승리하세요. 그리고 포인트와 상금을 획득하세요. 그리고 AWS re:Invent 2019에서 열리는 AWS DeepRacer Championship Cup 출전권도 받으세요.

 

AWS Free Tier를 사용하면 최대 10 시간동안 훈련을 무료로 진행할 수 있습니다. 그러니까 AWS DeepRacer League에 아무런 비용을 들이지 않고 참여해 보세요. 

 

Race Online       View Live Leaderboard  

 

 

AWS DEEPRACER TV

Take a step inside the AWS DeepRacer League. Episode 1 follows the competition to Amsterdam, featuring developers of all skill levels hoping to qualify for a chance to win the Championship Cup at AWS re:Invent 2019. Tune in now to learn more about their strategy and how you can build and tune a model for a chance to win!

 

AWS DeepRacer League를 향해 한걸음 내디뎌 보세요. 에피소드 1은 암스테르담에서의 경기가 나옵니다. AWS re:Invent 2019 에서 열리는 Championship Cup에서 우승하는 것을 목표로 하는 다양한 수준의 개발자들이 나옵니다. 그들의 전략에 대해 배워 보세요 그리고 여러분은 우승을 위해 어떻게 모델을 만들어 갈 것인지 생각해 보세요.

 

 

 

Pick a race

 

개발자는 매월 공개 될 유명한 raceways에서 영감을 얻은 가상 트랙을 통해 Virtual Circuit에서 경쟁함으로써 테스트에 자신의 기술을 적용 할 수 있습니다. re:Invent 2019에서 열리는 AWS DeepRacer Championship Cup에 대한 경비와 경품을 얻기 위해 경쟁 할 수 있습니다.

20 개의 AWS Summit 중 아무 Summit이나 선택해서 직접 참가하세요. (참여하고 싶으면 여러 Summit에 참여하실 수 있습니다.) 워크샵을 통해 re:MARS 및 re:Invent 2019에서 모델을 어떻게 만들고 트레이닝 시킬 지에 대해 도움을 드릴 겁니다. 여러분이 트레이닝 시킨 모델을 집으로 가져 가실 수도 있습니다. 그리고 그 모델을 테스트하고 엑스포에서 그것을 가지고 경쟁하실 수 있습니다.

 

See Full Schedule and Standings

 

Pick up some racing tips

 

기계 학습을 처음 사용 하던지 기존 스킬을 기반으로 준비하든, 우리는 당신이 경주 준비를하는 것을 도울 수 있습니다. e- 러닝 수업 인 AWS DeepRacer : 강화 학습 학습에 의해 시작할 수 있습니다. 약 90 분 후에 보강 학습 (자율 차량 교육에 이상적인 기계 학습의 한 분야)의 기본 사항과 AWS DeepRacer - 트랙을 누빌 준비가되었습니다!

 

Take the e-learning course

 

 

Race, win prizes, score points

 

Summit Circuit 레이스 또는 Virtual Circuit 레이스에서 경쟁하십시오. 경쟁하는 레이스 수에는 제한이 없습니다. Virtual Circuit 또는 Summit Circuit 레이스 중 하나만이라도 1등을 하면 라스베가스에서 열리는 AWS re:Invent에서 열리는 AWS DeepRacer final round에 참가하는 경비를 지원받으실 수 있습니다. 각 레이스의 10등까지는 AWS DeepRacer 자동차를 받으실 수 있습니다. 

각 레이스마다 참여하시면 포인트를 받게 됩니다. 2019년 말에 이 포인트들의 합계를 가지고 등수를 가립니다. 각 Circuit의 우승자에게는 re:Invent 2019의 AWS DeepRacer knockout(final) 라운드에 참가하는 경비를 지원 받으실 수 있습니다. 자세한 내용은 AWS DeepRacer 공식 규칙을 참조하십시오.


레이스에 참가하면 2019 AWS DeepRacer League Champion이 될 수 있습니다!

 

Learn more about points and prizes

 

 

 

2차 Virtual Race 오픈

 

Kumo Torakku Track

 

 

 

 

 

반응형


반응형

Stragit Track 에서 두번 훈련 시킨 모델을 Clone 해서 곡선이 있는 다른 트랙에서 훈련 시키기로 했다.

나머지 트랙 중 가장 간단한 트랙인 Oval Track에서 먼저 훈련을 시켰다.

 

 

reward_function을 약간 수정했는데....

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 45

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 2.0:
        reward *=0.80
    
    return float(reward)

 

일단 여긴 곡선 구간이 있으니 핸들 꺾는 걸 조금 더 여유를 주어야 겠다고 생각했다.

이전 직선 트랙에서는 15도로 제한을 뒀는데 여기서는 45도 까지 여유를 주었다.

그 이상 핸들을 급하게 꺾으면 점수가 20% 깎이도록 했다.

 

그리고 곡선구간에서는 아무래도 속도를 줄여야 하니 제한을 2.0으로 고쳤다.

이전엔 2.5 였다.

 

이렇게 고치고 나서 100분 동안 훈련을 시켰다.

 

한 30분 쯤 지나면서 부터 높은 reward가 나오기 시작했다.

그리고 reward 저점도 그 이후부터는 1.50k를 넘었다.

 

그 이후부터는 reward의 고점이 대략 8.0k 내외이고 그런 고점이 나오는 빈도수도 크게 변화를 보이지는 않은 것 같다.

 

아마 위 reward_function으로 이 구간에서는 그렇게 크게 performance가 발전하기는 힘들 것 같다.

 

reward_function을 조금씩 고쳐가며 계속 훈련을 하고 싶지만.. 한번 그렇게 하는데 별도로 돈을 내야하기 때문에 맘 놓고 여러가지를 시도 하지 못하겠다.

 

일단 평가 결과는 아래와 같다.

 

3번 시도 중 한번만 성공했고 실패한 것도 트랙을 35%만 돌았다.

점수가 아주 저조하다.

 

성공했을 때의 기록은 23.797초 이다.

 

 

일단 이 트랙은 이 정도면 됐고 다음 연습 트랙은 어제 끝난 AWS Deepracer League - Viertual Circuit London Loop 에서 사용한 London Loop Track에서 훈련을 시키기로 결정 했다.

 

 

이 리그는 4/29 부터 5/31 까지 한달간 진행된 리그이다.

나는 늦게 시작해서 이 리그에는 참가를 못 했다.

6월부터 시작하는 Vertual league에 참가할 계획이다.

 

일단 London Loop Track에서 사용할 reward_function은 아래처럼 고쳤다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 30

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 1.5:
        reward *=0.80
    
    return float(reward)

 

여기서도 핸들 각도와 스피드 제한 부분을 조금 수정했다.

 

일단 핸들 각도는 이전보다 좁은 30도를 줬다. 

이 트랙이 이전 트랙보다 조금 더 급한 커브가 있지만 속도를 더 낮추는 걸로 대비하기로 했다.

 

스피드는 이전에 2.0 의 제한을 두던것을 1.5로 낮췄다.

 

훈련시간은 큰 맘 먹고 300분으로 했다. 

그 결과는 아래와 같다.

 

 

여기도 보니까 30분 이후부터 조금씩 개선되는 것 같더니 1시간 이후부터 저점이 3.0K를 어느 정도 유지하는 싸이클을 보였다.

 

그 이후는 그게 개선되지는 않았지만 3시간 지나면서 최고점인 9.69K를 찍기 시작했다.

 

훈련 후 진행한 평가 결과는 아래와 같다.

 

 

3번 중 2번 완주 했고 기록은 24초 정도 이다.

실패한 1번도 트랙을 80% 진행했다.

Oval Track과 비교해서 아주 만족스런 결과이다.

 

좋다.

 

 

참고로   AWS Deepracer League - Viertual Circuit London Loop 수상자들의 기록은 다음과 같다.

 

 

9초,10초, 11초.... 24초인 내가 낄 자리는 없다.

쟤네들은 어떤 reward_function을 썼고 Hyperparameter configuration은 어떤 변동을 주었는지 그리고 어떤 훈련을 얼마나 시켰는지 궁금하다.

 

다음주 2차 Virtual League에서 사용하는 Track 이 발표되면 그 트랙에서 집중적으로 훈련을 시킬 계획이다.

반응형


반응형

오늘은 모델을 생성하고 Training 시키고 Evaluation까지 시키고 난 후 볼 수 있는 여러 정보들을 살펴 봤다.

 

우선 Reward Graph를 보면 Refresh 버튼 밑에 메뉴항목이 있다.

View in metrics와 View logs가 있는데..

 

일단 View in metrics로 가 보자.

 

그러면 Cloud Watch의 Total reward over time 페이지로 이동한다.

 

AWS Cloud Watch는 AWS 클라우드 서비스들에 대한 모니터링 정보를 제공하는 서비스이다.

 

Amazon CloudWatch is a monitoring service for AWS cloud resources and the applications you run on AWS. You can use Amazon CloudWatch to collect and track metrics, collect and monitor log files, set alarms, and automatically react to changes in your AWS resources.

 

이 Total Reward over time 페이지는 아래와 같다.

 

Reward Graph가 좀 더 자세하게 나오고 그 아래에는 뭔지 모를 4개의 탭이 있고 더 뭔지 모를 여러 정보들이 있다.

 

뭐 별로 눈길을 끄는게 없어서 다음으로 패스.

 

View logs를 클릭 해 봤다.

 

역시 AWS Cloudwatch 서비스 페이지로 넘어갔다.

 

 

 

 

여기에는 로그 정보들이 있다.

매일 코딩을 하다보면 어쩔 수 없이 뚫어져라 볼 수 밖에 없는 게 로그 정보들이라서 이건 좀 친숙하다.

 

 

우선 첫번째 링크는 Lamda로그인 것 같은데 여기엔 별 정보가 없었다.

 

두 번째 로그는 시뮬레이션 관련 로그인 것 같다.

이 정보들을 활용하는 법을 알면 유용한 정보일 수 있을 것 같다.

아직은 잘 몰라서 그냥 이런게 있다는 것만 알고 넘어간다.

 

마지막 세번째 링크가 Training 관련 로그이다.

 

여기엔 좀 뭔가 알아 먹을 것 같은 로그 정보들이 있다.

이건 직선 트랙에 디폴트 reward_function 을 사용한 트레이닝 로그인데 여기에 에피소드와 이터레이션 정보가 있다.

 

30분간 트레이닝을 시켰는데 마지막 에피소드는 372 이다.

아마 372번 훈련을 한 것이다.

 

1개의 iteration에는 20개의 에피소드가 있다. 

그래서 총 18개의 iteration이 있다.

 

각 에피소드 별로 Total Reward와 Steps 정보가 있다.

 

이 로그에는 대충 이런 정보들이 있다.

 

그 외에 이 로그 시작 부분에 각 종 환경 변수나 파라미터 정보들이 있다.

 

 

 

 

 

그 다음 Evaluation section에는 평가 결과 정보가 있다.

평가는 3번 하는 것 같다.

평가 작업은 계속 할 수 있는데 이 서비스는 별도의 요금을 내는 것 같아서 여러번 시도하지는 않았다.

 

그 다음 Training Configuration section에는 여러 config 정보를 볼 수 있다.

 

Reward function의 Show 버튼을 누르면 이 모델에서 사용한 Reward function을 볼 수 있다.

그리고 그 밑에 Action space 정보를 볼 수 있는 버튼이 있다.

 

Framewark 은 Tensorflow를 사용했고 Reinforcement learning algorithm은 PPO를 사용했다는 정보가 있다.

 

그리고 마지막은 Hyperparameter 정보들이 있다.

 

지금까지 직선 트랙에서 두 번 훈련 시켰다.

 

다음은 곡선이 들어간 트랙에서 훈련을 시켜보기로 했다.

 

 

 

 

 

 

반응형


반응형

본격적으로 AWS Deepracer를 시작했다.

첫번째 모델을 만들었다.

 

일단 트랙은 제일 간단한 것으로 선택 하고 Speed는 5로 선택.
직선도로니까 빠르게 달리게 만드는게 더 좋을 것 같아서.
나머지는 다 디폴트.


Reward_function도 그냥 디폴트 사용하고 시간은 30분
참고로 디폴트 함수는 아래와 같다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    
    # Calculate 3 markers that are at varying distances away from the center line
    marker_1 = 0.1 * track_width
    marker_2 = 0.25 * track_width
    marker_3 = 0.5 * track_width
    
    # Give higher reward if the car is closer to center line and vice versa
    if distance_from_center <= marker_1:
        reward = 1.0
    elif distance_from_center <= marker_2:
        reward = 0.5
    elif distance_from_center <= marker_3:
        reward = 0.1
    else:
        reward = 1e-3  # likely crashed/ close to off track
    
    return float(reward)

 

소스코드를 보니 트랙 중앙선 가까이 가면 점수(reward)를 더 많이 주는 간단한 로직이다.

30분 트레이닝 시키고 곧바로 Evaluate
결과는 조금 있다가…

 

 

 


이 첫번째 모델을 clone 해서 두번째 모델을 만들었다.
다 똑같고 reward function 함수만 내가 원하는 대로 조금 바꾸었다.

 

def reward_function(params):
    '''
    Example of rewarding the agent to follow center line
    '''
    reward=1e-3
    
    # Read input parameters
    track_width = params['track_width']
    distance_from_center = params['distance_from_center']
    steering = params['steering_angle']
    speed = params['speed']
    all_wheels_on_track = params['all_wheels_on_track']
    
    if distance_from_center >=0.0 and distance_from_center <= 0.03:
        reward = 1.0
    
    if not all_wheels_on_track:
        reward = -1
    else:
        reward = params['progress']
        
    # Steering penality threshold, change the number based on your action space setting
    ABS_STEERING_THRESHOLD = 15

    # Penalize reward if the car is steering too much
    if steering > ABS_STEERING_THRESHOLD:
        reward *= 0.8
        
    # add speed penalty
    if speed < 2.5:
        reward *=0.80
    
    return float(reward)

 

이전에 썼던 디폴트 함수와는 다르게 몇가지 조건을 추가 했다.
일단 중앙선을 유지하면 좀 더 점수를 많이 주는 것은 좀 더 간단하게 만들었다.
이 부분은 이전에 훈련을 했으니까 이 정도로 해 주면 되지 않을까?
그리고 아무 바퀴라도 트랙 밖으로 나가면 -1을 하고 모두 트랙 안에 있으면 progress 만큼 reward를 주었다.
Progress는 percentage of track completed 이다.
직진해서 결승선에 더 가까이 갈 수록 점수를 더 많이 따도록 했다.
이건 차가 빠꾸하지 않고 곧장 결승점으로 직진 하도록 만들기 위해 넣었다.
그리고 갑자기 핸들을 과하게 돌리면 차가 구르거나 트랙에서 이탈할 확률이 높으니 핸들을 너무 과하게 돌리면 점수가 깎이도록 했다. (15도 이상 핸들을 꺾으면 점수가 깎인다.)
그리고 속도도 너무 천천히 가면 점수를 깎는다.

속도 세팅이 최대 5로 만들어서 그 절반인 2.5 이하고 속도를 줄이면 점수가 깎인다.


이렇게 조건들을 추가하고 Training 시작.
이건 좀 복잡하니 트레이닝 시간을 1시간 주었다.

이 두개의 모델에 대한 결과는…

 

딱 보니 첫번째 디폴트 함수를 사용했을 때는 시간이 갈수록 결과가 좋게 나왔다.
그런데 두번째는 시간이 갈수록 실력이 높아지지는 않는 것 같다.


너무 조건이 여러개 들어가서 그런가?

 

 


생각해 보니 조건을 많이 넣는다고 좋은 것은 아닌것 같다.
일반적으로 코딩을 하다 보면 예외 상황을 만들지 않게 하기 위해 조건들을 아주 많이 주는 경향이 있는데 이 인공지능 쪽은 꼭 조건을 많이 줄 필요는 없을 것 같다.


앞으로 인공지능 쪽을 하다보면 일반 코딩에서의 버릇 중에 고칠 것들이 많을 것 같다.
Evaluation 결과를 보면 두개의 차이가 별로 없다. 
두 모델 모두 3번중 2번 완주 했고 완주시간도 비슷한 것 같다.
조건을 쪼금 더 준 Model 2 가 좀 더 낫긴 하네. (0.2 ~0.3 초 더 빠르다.)
다음은 곡선이 있는 다른 트랙으로 훈련을 시킬 계획이다.


그런데 곡선이 있는 트랙에서는 스피드가 무조건 빠르다고 좋은 건 아닌 것 같다.
내가 스피드를 5로 주었는데 Clone을 만들어서 할 때는 이 스피드를 조절하지 못하는 것 같다.


곡선 구간에서는 reward_function을 어떻게 주어야 하지?

반응형


반응형

AWS DeepRacer 공부를 시작하고 나서 뜻밖의 요금이 징수되서 조금 놀랐다.

지난주 매일 1달러씩 부과 되던 NAT Gateways 서비스를 언제 세팅 했는지 몰랐었다.

여하튼 아마존 Support 서비스의 도움을 받아서 해당 서비스를 Delete 한 이후 요금은 더이상 부과 되지는 않았는데...

문제는 그걸 지우고 난 이후 Deepracer model을 생성하면 에러가 발생해서 일을 더이상 진행 할 수가 없었다.

 

도저히 안되서 새로운 account를 생성하고 Deepracer Model을 하나 생성했다.

 

그랬더니 모델과 더불어 NAT Gateways가 생성되더라.

이제 알았다. 처음 DeepRacer를 시작하기 위해 account resources를 생성할 때 이 NAT Gateway가 생성된다는 것을....

 

이 단계를 완료하면 NAT Gateways가 생성돼 매일 1달러씩 청구된다.

참고로 아래는 DeepRacer 모델을 하나 생성하면 청구되는 금액들이다.

 

 

* Data Transfer에서 $0.010 per GB - regional data transfer - in/out/between EC2 AZs or using elastic IPs or ELB 가 5기가가넘어서 5센트가 청구됐다. 

* 그 다음 EC2에서 NAT Gateway가 생성과 연계해서 2.10 달러가 청구 됐다.

* 여기서 NAT Gateway는 매일 1달러씩 청구되게 돼 있다.

* 그 다음은 시뮬레이터 서비스인 RoboMaker 서비스에 대해 1.52달러가 청구됐고 SageMaker는 30센트가 청구됐다.

 

다른 서비스들은 사용하면 사용한 시간만큼만 내는데 NAT Gateway는 24시간 계속 돌아가기 때문에 매일 1불씩 내야 한다.

사용하지 않을 때 Stop 할 수도 없는 것 같다.

 

하루에 1달러이면 아무것도 아니라고 생각할 수 있지만... 아무것도 하지 않는데도 청구가 되니 속이 쓰렸다.

 

그래서 AWS Support Case를 하나 더 Raise 했다.

 

오늘 아침에 했는데 퇴근 할 때 쯤 답변이 오더라구.

 

 

다음은 답변 내용...

 

Hey there! This is Merlyn, your AWS Billing & Accounts specialist. I hope you are having a wonderful day! I understand you have some concerns about the DeepRacer pricing and you bill. Worry not as I'm here to help.


DeepRacer의 가격 책정과 청구서와 관련 우려가 있다는 것에대해 이해합니다. 걱정마세요. 제가 도와드릴테니까요.

With AWS DeepRacer console services, there are no charges for driving the AWS DeepRacer car or upfront charges. You will only pay for the AWS services you use. You will be billed separately by each of the AWS services used to provide the AWS DeepRacer console services such as creating and training your models, storing your models and logs, and evaluating them, including racing them in the virtual simulator or deploying them to their AWS DeepRacer car. You will see the bill for each service on your monthly billing statement.

AWS DeepRacer console services는 AWS DeepRacer 차량을 driving 하는데에 대한 가격 책정이나 선불로 어떠한 돈을 낼 필요가 없습니다. 당신이 AWS services를 사용한 것에 대한 요금만 지불 하시면 됩니다. AWS DeepRacer console services를 통해 사용하시는 AWS services들에 대해 각각의 사용료가 따로 청구 될 것입니다. 예를 들어 당신의 모델들을 생성하고 훈련하는 것 그리고 그 모델들이나 로그들을 저장하는 것, 그 모델들을 평가하는 작업, 가상 시뮬레이터에서 모델의 레이싱을 하거나  AWS DeepRacer car에 배치하는 일들에 대해 따로 사용료가 부과 됩니다. 

Upon first use of AWS DeepRacer simulation in the AWS console, new customers will get 10 hours of Amazon SageMaker training, and 60 Simulation Unit (SU) hours for Amazon RoboMaker in the form of service credits; $6 for SageMaker, $24 for RoboMaker and $34 for NAT Gateway. The service credits are available for 30 days and applied at the end of the month. A typical AWS DeepRacer simulation uses up to six SUs per hour, thus you will be able to run a typical AWS DeepRacer simulation for up to 10 hours at no charge.


AWS console에서 AWS DeepRacer simulation을 처음 사용하는 새 고객에게는 10시간 동안 Amazon SageMaker training과 Amazon RoboMaker에 대해 60 Simulation Unit (SU) 시간에 대해 service credits이라는 형태로 무료 사용하실 수 있는 기회를 드립니다. SageMaker는 $6 , RoboMaker $24 그리고  NAT Gateway는 $34 입니다. 이 service credits은 30일간 사용 가능하고 그 달의 말에 적용됩니다. 일반적으로  AWS DeepRacer simulation 사용은 시간당 six SUs이므로 당신은 AWS DeepRacer simulation을 10시간 동안 무료로 사용하실 수 있습니다. 

Please visit the link below for more pricing information:

자세한 가격 정보는 아래 링크를 참조하세요.

https://aws.amazon.com/deepracer/pricing/ 

This inquiry is a bit out of our scope. Here in the Billing and Accounts department we don’t handle technical questions. Please note that AWS unbundles technical support in order to lower the prices of the services themselves instead of billing it to all customers disregarding if they’d like to use it or not. However, if technical support is required, I would like to tell you we offer several Premium Support plans starting at just $29 a month, which enables you to speak to an engineer by email, chat, or phone depending on what support plan you choose.


당신의 요청 중 일부는 우리의 권한을 벗어나는 부분이 있습니다. 저희 Billing and Accounts department에서는 기술적인 질문은 다루지 않습니다. 저희는 모든 고객에게 비용 지불의 부담을 주지 않고 저렴한 가격을 유지하기 위해 기술 부문의 Support는 분리해서 다루고 있습니다. 만약 기술적인 support를 원하시면 월 $29 부터 시작되는 Premium Support plan 서비스들이 있습니다. 이 유료 기술 지원 서비스를 이용하시면 이메일, 채팅 그리고 전화등 여러분이 편한 방식으로 엔지니어들과 소통을 할 수 있습니다.

All Premium Support plans include direct access to Support Engineers, and these plans offer a tailored support experience that allows you to select the support level that best fits your needs. More information including pricing and how to sign up can be found here:


모든 Premium Support plan 들에는 Support Engineers과의 직접 access 권한이 포함되며 이러한 플랜들에서는 사용자의 요구 사항에 가장 적합한 서포트 레벨을 선택할 수 있는 맞춤 지원 서비스가 제공 됩니다. 가격 정책 및 가입 방법에 대한 자세한 정보는 여기를 참조하세요.

https://aws.amazon.com/premiumsupport/pricing/ 

You can also search the Amazon Web Services Developer forums or post a new question. Our technical staff and the Amazon Web Services developer community participate in the forums regularly and might be able to help you. Generally, questions are responded to in about a day, though there is not a guaranteed response time.


그 외에  Amazon Web Services Developer forums에서 궁금한 내용을 검색해서 찾는 방법도 있습니다. 또한 새로운 질문을 이곳에 올릴 수도 있구요. Our technical staff와 Amazon Web Services developer community에 참여하는 개발자들로 부터 지원을 받으실 수도 있을 겁니다. 일반적으로 하루 정도 기다리면 답변을 받습니다. (응답 시간에 대한 보장은 없지만요.)

https://forums.aws.amazon.com/index.jspa 

Finally, you may also want to check out our AWS Support Knowledge Center and AWS Documentation pages located here:  

마지막으로 AWS Support Knowledge Center 및 AWS Documentation 페이지를 참조하십시오.

https://aws.amazon.com/premiumsupport/knowledge-center/  
https://aws.amazon.com/documentation/ 

I certainly want you to have the best experience while using our services, so please feel free to let me know if you have any other concern in the meantime, it will be an honor to keep on assisting you. On behalf of Amazon Web Services, I wish you Happy Cloud Computing!

 

Best regards,

Merlyn N.

Amazon Web Services

====================================================================
Learn to work with the AWS Cloud. Get started with free online videos and self-paced labs at 
http://aws.amazon.com/training/ 
====================================================================

Amazon Web Services, Inc. and affiliates

 

 

 

뭐 내용을 읽어보니 어쩔 수 없는 것 같다.

 

어쨌든 한달 정도는 공짜인 것 같으니 거기에 위안을 삼아야지...

 

AWS DeepRacer forum 에 갔더니 나처럼 모델 생성시 Error가 난다는 글이 몇개 눈에 띄었다.

아마도 NAT Gateways를 delete 해서 그런게 아닌지...

 

이 문제 때문인지 몰라도 어제부터 아마존에서 뭔가 이슈를 처리하느라 Training과 evaluation 일을 할 수 없다는 메세지가 뜨더라.

 

 

이 investigation이 위 문제와 관련이 있기를 바라고 또 그 결과로 NAT Gateways 비용 청구와 관련해서 좀 더 전향적인 방안이 제시 됐으면 좋겠다.

 

하루 1불씩 무조건 부과되는건 쫌 부담 스럽다.

내가 필요할 때만 해당 서비스를 사용하고 거기에 대한 비용만 지불할 수 있게 해 달라... 아마존아......

  

반응형


반응형

Hands-on Exercise 1: Model Training Using AWS DeepRacer Console

 

This is the first of four exercises that you will encounter in this course. This first exercise guides you through building, training, and evaluating your first RL model using the AWS DeepRacer console. To access the instructions for three of these exercises, download and unzip this course package. For this particular exercise, find and open the relevant PDF file and follow the steps within to complete the exercise.

*Note: This exercise is designed to be completed in your AWS account. AWS DeepRacer is part of AWS Free Tier, so you can get started at no cost. For the first month after sign-up, you are offered a monthly free tier of 10 hours of Amazon SageMaker training and 60 simulation units of Amazon RoboMaker (enough to cover 10 hours of training). If you go beyond those free tier limits, you will accrue additional costs. For more information, see the AWS DeepRacer Pricing page.

 

Hands-on Exercise 1- Model Training Using AWS DeepRacer Console.pdf
0.23MB

 

 

 

 

Hands-on Exercise 2- Advanced Model Training Using AWS DeepRacer Console.pdf
0.25MB

 

 

For feedback, suggestions, or corrections, email us at aws-course-feedback@amazon.com.

 

 

Hands-on Exercise 3- Distributed AWS DeepRacer RL Training using Amazon SageMaker and AWS RoboMaker.pdf
0.46MB

 

SageMakerForDeepRacerSetup.yaml
0.01MB

 

AWSTemplateFormatVersion: "2010-09-09"
Description: 'AWS DeepRacer: Driven by Reinforcement Learning'
Parameters:
  SagemakerInstanceType:
    Description: 'Machine Learning instance type that should be used for Sagemaker Notebook'
    Type: String
    AllowedValues:
      - ml.t2.medium
      - ml.t2.large
      - ml.t2.xlarge
      - ml.t3.medium
      - ml.t3.large
      - ml.t3.xlarge
      - ml.m5.xlarge
    Default: ml.t3.medium
  CreateS3Bucket:
    Description: Create and use a bucket created via this template for model storage
    Default: True
    Type: String
    AllowedValues:
      - True
      - False
    ConstraintDescription: Must be defined at True|False.
  VPCCIDR:
    Description: 'CIDR Block for VPC (Do Not Edit)'
    Type: String
    Default: 10.96.0.0/16
  PUBSUBNETA:
    Description: 'Public Subnet A (Do Not Edit)'
    Type: String
    Default: 10.96.6.0/24
  PUBSUBNETB:
    Description: 'Public Subnet B (Do Not Edit)'
    Type: String
    Default: 10.96.7.0/24
  PUBSUBNETC:
    Description: 'Public Subnet C (Do Not Edit)'
    Type: String
    Default: 10.96.8.0/24
  PUBSUBNETD:
    Description: 'Public Subnet D (Do Not Edit)'
    Type: String
    Default: 10.96.9.0/24
  S3PathPrefix:
    Type: String
    Description: 'Bootstrap resources prefix'
    Default: 'awsu-spl-dev/spl-227'
  S3ResourceBucket:
    Type: String
    Description: 'Bootstrap S3 Bucket'
    Default: 'aws-training'
Conditions:
  CreateS3Bucket: !Equals [ !Ref CreateS3Bucket, True ]
  #  NoCreateS3Bucket: !Equals [ !Ref CreateS3Bucket, False ]
Resources:

# Defining the VPC Used for the sanbox ENV, and notebook instance
  VPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: !Ref VPCCIDR
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      Tags:
        - Key: Name
          Value: 'DeepRacer Sandbox'
# There is a few calls made to public to download supporting resources
  InternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    DependsOn: VPC
    Properties:
      Tags:
        - Key: Name
          Value: 'DeepRacer Sandbox IGW'
# Attached this IGW to the sanbox VPC
  AttachGateway:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    DependsOn:
      - VPC
      - InternetGateway
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway
# Default setting in the notebook is to use Public IP address to communicate
# between instances running the simulation, and the instances collecting and
# processing. A NatGW could have been used with added costs, but would allow for
# use of private IP address.

# Found in testing that not all ML instance types may not be deployed or avaliable
# in all AZ's within a given region. We are using the newest instance family of T3
  PublicSubnetA:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETA
      AvailabilityZone: !Select
        - '0'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox - Public Subnet - A'
  PublicSubnetB:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETB
      AvailabilityZone: !Select
        - '1'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Subnet - B'
  PublicSubnetC:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETC
      AvailabilityZone: !Select
        - '2'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Subnet - C'
  PublicSubnetD:
    Type: 'AWS::EC2::Subnet'
    DependsOn: VPC
    Properties:
      VpcId: !Ref VPC
      CidrBlock: !Ref PUBSUBNETD
      AvailabilityZone: !Select
        - '3'
        - !GetAZs ''
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Subnet - D'
# Define the Public Routing Table
  PublicRouteTable:
    Type: 'AWS::EC2::RouteTable'
    DependsOn:
      - VPC
      - AttachGateway
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: 'Deepracer Sandbox Public Routing Table'
# And add in the default route to 0.0.0.0/0
  PublicRouteIGW:
    Type: 'AWS::EC2::Route'
    DependsOn:
      - PublicRouteTable
      - InternetGateway
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
# Attach the routing table to each of the subnets
  PublicRouteTableAssociationA:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetA
      RouteTableId: !Ref PublicRouteTable
  PublicRouteTableAssociationB:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetB
      RouteTableId: !Ref PublicRouteTable
  PublicRouteTableAssociationC:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetC
      RouteTableId: !Ref PublicRouteTable
  PublicRouteTableAssociationD:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref PublicSubnetD
      RouteTableId: !Ref PublicRouteTable
# Define a S3 endpoint for all the S3 traffic during training
  S3Endpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref VPC
      RouteTableIds:
        - !Ref PublicRouteTable
      ServiceName: !Join
        - ''
        - - com.amazonaws.
          - !Ref 'AWS::Region'
          - .s3
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal: '*'
            Action:
              - 's3:*'
            Resource:
              - '*'
# This exercise is going to need a bucket to store any file generated from training
# There is a conditions to evaluate if the PRAM is true, else this resource would
# not be created.
  SandboxBucket:
    Type: 'AWS::S3::Bucket'
    DeletionPolicy: Retain
    Condition: CreateS3Bucket
    Properties:
      BucketName:
        Fn::Join:
          - "-"
          - - deepracer-trainingexercise
            - Ref: AWS::Region
            - Ref: AWS::AccountId
# Sagemaker is going to be making calls to Robomaker to launch the sim, and
# Sagemaker to launch the training insance. This requries AWS credentals. A
# Principal of sagemaker and robomaker needs to be assiged as both service will
# assuming this role. Default Sagemaker full access and s3 access is needed.
  SageMakerNotebookInstanceRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - sagemaker.amazonaws.com
                - robomaker.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonSageMakerFullAccess'
      Path: /
      Policies:
        - PolicyName: DeepRacerPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action: [ 's3:*',
                          'iam:GetRole' ]
                Resource: '*'
# This is how the notebook gets loaded on to sagemaker. There is a zip file with
# with the needed files, and a second http call to pull down the notebook.
# This is only done "OnCreate" - when the sagemaker instance is first deployed
# You can can the script get run "OnStart" (when a sagemaker instance changes
# from a stopped state to a running state). This would automaticlly update file
# to be the latest form source, but could over write changes applied during
# your testing
  SageMakerNotebookInstanceLifecycleConfig:
    Type: 'AWS::SageMaker::NotebookInstanceLifecycleConfig'
    Properties:
  #    OnStart:
  #      - Content:
  #          Fn::Base64:
  #            #!/bin/bash
  #            !Sub |
  #            cd SageMaker
  #            chown ec2-user:ec2-user -R /home/ec2-user/SageMaker

      OnCreate:
        - Content:
            Fn::Base64:
              !Sub |
              cd SageMaker
              curl -O https://us-west-2-${S3ResourceBucket}.s3.amazonaws.com/${S3PathPrefix}/scripts/rl_deepracer_robomaker_coach.ipynb
              curl -O https://us-west-2-${S3ResourceBucket}.s3.amazonaws.com/${S3PathPrefix}/scripts/rl_deepracer_robomaker_coach.zip
              unzip rl_deepracer_robomaker_coach.zip
              chown ec2-user:ec2-user -R /home/ec2-user/SageMaker
# Security Group for sagemaker instance running in this VPC
  SagemakerInstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Sagemaker Security Group
      VpcId: !Ref VPC
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
      - IpProtocol: udp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
      SecurityGroupEgress:
      - IpProtocol: tcp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
      - IpProtocol: udp
        FromPort: 1
        ToPort: 65535
        CidrIp: !Ref VPCCIDR
# Creating the Sagemaker Notebook Instance
  SageMakerNotebookInstance:
    Type: 'AWS::SageMaker::NotebookInstance'
    Properties:
      #NotebookInstanceName: 'DeepracerSagemakerSandbox'
      NotebookInstanceName: !Join ["-", ["DeepRacerSagemakerSandbox", !Ref "AWS::StackName"]]
      SecurityGroupIds:
        - !GetAtt
          - SagemakerInstanceSecurityGroup
          - GroupId
      InstanceType: !Ref SagemakerInstanceType
      SubnetId: !Ref PublicSubnetA
      Tags:
        - Key: Name
          Value: 'DeepRacer Sandbox'
      LifecycleConfigName: !GetAtt
          - SageMakerNotebookInstanceLifecycleConfig
          - NotebookInstanceLifecycleConfigName
      RoleArn: !GetAtt
          - SageMakerNotebookInstanceRole
          - Arn
Outputs:
  # Display the name of the bucekt that was created from this CFN Stack
    ModelBucket:
      Condition: CreateS3Bucket
      Value: !Ref SandboxBucket
  # URL to get to the Sagemaker UI, and find the Jupyter button. 
    SagemakerNotebook:
      Value:
        !Sub |
          https://console.aws.amazon.com/sagemaker/home?region=${AWS::Region}#/notebook-instances/${SageMakerNotebookInstance.NotebookInstanceName}

반응형
이전 1 2 3 다음